johnson-trotter

0.1.1 • Public • Published

johnson-trotter.js npm Version Build Status Coverage Status

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

License

MIT

Package Sidebar

Install

npm i johnson-trotter

Weekly Downloads

3

Version

0.1.1

License

MIT

Last publish

Collaborators

  • yuanqing