Skip to content

Instantly share code, notes, and snippets.

@bobwei
Created May 24, 2016 12:44
Show Gist options
  • Select an option

  • Save bobwei/2f26d0107513e25b902afe6c99272575 to your computer and use it in GitHub Desktop.

Select an option

Save bobwei/2f26d0107513e25b902afe6c99272575 to your computer and use it in GitHub Desktop.
'use strict';
/*
arr = [1, 2, 3]
for each element in arr, create subArr
for i = 1 => subArr = [2, 3]
for i = 2 => subArr = [1, 3]
for each subArr, get permutations
(ex: [2, 3] => [ [2, 3], [3, 2] ])
for each permutation in permutations, get an array started with arr[i]
(ex: 1, [ [2, 3], [3, 2]] => [[1, 2, 3], [1, 3, 2]])
*/
var getPermutation = (arr) => {
if (arr.length <= 1) {
return [arr];
}
let output = [];
arr.forEach((n, i) => {
let subArr = [...arr.slice(0, i), ...arr.slice(i + 1)];
let permutations = getPermutation(subArr);
permutations.forEach((permutation) => {
output.push([arr[i], ...permutation]);
});
});
return output;
};
console.log(getPermutation([1, 2, 3, 4]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment