I have an array of n different elements in javascript, I know there are n! possible ways to order these elements. I want to know what\'s the most effective (fastest) algorit
This is my version based on le_m's code:
function permute(array) {
Array.prototype.swap = function (index, otherIndex) {
var valueAtIndex = this[index]
this[index] = this[otherIndex]
this[otherIndex] = valueAtIndex
}
var result = [array.slice()]
, length = array.length
for (var i = 1, heap = new Array(length).fill(0)
; i < length
;)
if (heap[i] < i) {
array.swap(i, i % 2 && heap[i])
result.push(array.slice())
heap[i]++
i = 1
} else {
heap[i] = 0
i++
}
return result
}
console.log(permute([1, 2, 3]))
This is my recursive JavaScript implementation of the same algorithm:
Array.prototype.swap = function (index, otherIndex) {
var valueAtIndex = this[index]
this[index] = this[otherIndex]
this[otherIndex] = valueAtIndex
}
Array.prototype.permutation = function permutation(array, n) {
array = array || this
n = n || array.length
var result = []
if (n == 1)
result = [array.slice()]
else {
const nextN = n - 1
for (var i = 0; i < nextN; i++) {
result.push(...permutation(array, nextN))
array.swap(Number(!(n % 2)) && i, nextN)
}
result.push(...permutation(array, nextN))
}
return result
}
console.log([1, 2, 3].permutation())