Permuations
Last updated
Last updated
💾 程式:codesandbox - Permutations
/**
* find all the permutations of an array.
* @param {any[]} arr - array (of distinct elements)
*/
export function permutations(arr) {
// base case:
if (arr.length === 1) return [arr];
// recursive case:
// |ABC = A|BC + B|AC + C|AB
// hint: A|BC means fix A, permute BC.
return arr
.map((x, i) => {
let subarr = arr.slice(); // copy array
subarr.splice(i, 1); // remove `x` in place
return permutations(subarr).map((p) => [x, ...p]);
})
.reduce((union, ps) => [...union, ...ps], []);
}
matrix methodsfunctions