Created
December 10, 2015 06:53
-
-
Save highercomve/0e80af939a1d63ee61b3 to your computer and use it in GitHub Desktop.
JS Array permutation
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
| function permute(arr) { | |
| if (arr.length === 2) { | |
| return [arr.slice(), arr.slice().reverse()] | |
| } | |
| return arr.map(function(element, index, array) { | |
| var new_array = array.slice() | |
| var last_element = new_array.splice(index, 1) | |
| return permute(new_array).map(function(x) { | |
| return last_element.concat(x) | |
| }) | |
| }).reduce(function(a, b) { | |
| return a.concat(b) | |
| }) | |
| } | |
| Array.permute = permute | |
| Array.prototype.permute = function() { | |
| return Array.permute(this) | |
| } |
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
| function permute(arr) { | |
| if (arr.length === 2) { | |
| return [arr.slice(), arr.slice().reverse()] | |
| } | |
| return [].concat.apply([], arr.map(function(element, index, array) { | |
| var new_array = array.slice() | |
| var last_element = new_array.splice(index, 1) | |
| return Array.prototype.map.apply(permute(new_array), [ | |
| function(x) { | |
| return last_element.concat(x) | |
| } | |
| ]) | |
| })) | |
| } | |
| Array.permute = permute | |
| Array.prototype.permute = function() { | |
| return Array.permute(this) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment