Skip to content

permutations

Subhajit Sahu edited this page Nov 20, 2022 · 21 revisions

List all possible permutations.

Similar: randomPermutation, permutations, hasPermutation.


function permutations(x, n)
// x: an array
// n: number of values [-1 ⇒ any]
const array = require('extra-array');

[...array.permutations([1, 2])];
// → [ [], [ 1 ], [ 2 ], [ 1, 2 ], [ 2, 1 ] ]

[...array.permutations([1, 2, 3])];
// → [
//   [],          [ 1 ],
//   [ 2 ],       [ 3 ],
//   [ 1, 2 ],    [ 1, 3 ],
//   [ 2, 1 ],    [ 2, 3 ],
//   [ 3, 1 ],    [ 3, 2 ],
//   [ 1, 2, 3 ], [ 1, 3, 2 ],
//   [ 2, 1, 3 ], [ 2, 3, 1 ],
//   [ 3, 1, 2 ], [ 3, 2, 1 ]
// ]

[...array.permutations([1, 2, 3], 2)];
// → [ [ 1, 2 ], [ 1, 3 ], [ 2, 1 ], [ 2, 3 ], [ 3, 1 ], [ 3, 2 ] ]


References

Clone this wiki locally