Created
May 24, 2016 12:44
-
-
Save bobwei/2f26d0107513e25b902afe6c99272575 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| '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