johnson-trotter
v0.1.1
Published
An implementation of the Johnson-Trotter permutation algorithm.
Downloads
5
Maintainers
Readme
johnson-trotter.js
An implementation of the Johnson-Trotter permutation algorithm.
Usage
To iterate over the permutations of a given array, simply do:
var permute = require('johnson-trotter');
var arr = ['foo', 'bar', 'baz'];
var iter = permute(arr);
while (iter.hasNext()) {
iter.next();
//=> ['foo', 'bar', 'baz']
//=> ['foo', 'baz', 'bar']
//=> ['baz', 'foo', 'bar']
//=> ['baz', 'bar', 'foo']
//=> ['bar', 'baz', 'foo']
//=> ['bar', 'foo', 'baz']
}
Note that:
- Permutations are generated on-the-fly on every call to
next
. - Each permutation is a new array containing elements of the original array. The original array (ie.
arr
, in our example) is unmodified.
API
var permute = require('johnson-trotter');
var iter = permute(arr)
Initialises the iterator.
arr
— The array to generate permutations for.
iter.hasNext()
Returns true
if there are more permutations in the iteration.
iter.next()
Returns the next permutation in the iteration, or null
if there are no more permutations in the iteration. The returned array is a new array containing elements of the original array.
iter.reset()
Resets the iterator.
Installation
Install via npm:
$ npm i --save johnson-trotter
Changelog
- 0.1.0
- Initial release