Skip to content

Instantly share code, notes, and snippets.

@AaronFlower
Created May 4, 2019 01:46
Show Gist options
  • Save AaronFlower/e75bade88482eec632ee171c5c3b063c to your computer and use it in GitHub Desktop.
Save AaronFlower/e75bade88482eec632ee171c5c3b063c to your computer and use it in GitHub Desktop.
permutation
function permutation(arr, choosen, res) {
if (arr.length === 0) {
let b = []
Object.assign(b, choosen)
res.push(b)
return
}
for (var i = arr.length - 1; i >= 0; i--) {
// choose
var tmp = arr[i]
choosen.push(tmp)
arr.splice(i, 1)
// explore
permutation(arr, choosen, res)
// un-choose
choosen.splice(choosen.length - 1, 1)
arr.splice(i, 0, tmp)
}
}
let res = []
permutation(["a", "b", "c"], [], res)
console.log(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment