permutation-sjt
Version:
A quite fast non-recursive permutation algorithm, Steinhaus–Johnson–Trotter algorithm (Even's speedup)
53 lines (52 loc) • 1.73 kB
TypeScript
/**
* Steinhaus–Johnson–Trotter algorithm, Even's speedup
* https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm
*
*
* The Steinhaus–Johnson–Trotter algorithm or Johnson–Trotter algorithm generates
* all of the permutations of n elements. Each permutation in the sequence that
* it generates differs from the previous permutation by swapping two adjacent
* elements of the sequence.
*
* An improvement of the Steinhaus–Johnson–Trotter algorithm by Shimon Even
* provides an improvement to the running time
* of the algorithm by storing additional information for each element in the
* permutation: its position, and a direction (positive, negative, or zero) in which
* it is currently moving.
*/
export declare class Permutation {
private n;
private start;
private numbers;
private directions;
private positions;
private terminated;
/**
*
* @param n numbers in the arrray 1..n
*/
constructor(n: number, start?: number);
/**
* Checks if there is a permutation to return.
*
* @returns
*/
hasNext(): boolean;
/**
* Returns the next permutation of the Steinhaus–Johnson–Trotter algorithm,
* starting with [1,2,3, ..., n].
*
* Returns undefined if the permutations have been exhausted.
*
* @returns the next permutation or undefined
*/
next(): number[];
/**
* At each step, the algorithm finds the greatest element with a nonzero direction,
* and swaps it in the indicated direction.
*
* When all numbers become unmarked, the algorithm terminates.
*/
private generateNext;
private swapWithNextElementInDirection;
}