Skip to content

Instantly share code, notes, and snippets.

@highercomve
Created December 10, 2015 06:53
Show Gist options
  • Select an option

  • Save highercomve/0e80af939a1d63ee61b3 to your computer and use it in GitHub Desktop.

Select an option

Save highercomve/0e80af939a1d63ee61b3 to your computer and use it in GitHub Desktop.
JS Array permutation
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)
}
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