var swap = function (array, pos1, pos2) {
var temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
};
var heapsPermute = function (array, output, n) {
n = n || array.length; // set n default to array.length
if (n === 1) {
output(array);
} else {
for (var i = 1; i <= n; i += 1) {
heapsPermute(array, output, n - 1);
if (n % 2) {
var j = 1;
} else {
var j = i;
}
swap(array, j - 1, n - 1); // -1 to account for javascript zero-indexing
}
}
};
// For testing:
var print = function(input){
console.log(input);
}
heapsPermute(['a', 'b', 'c', 'd'], print);
Hello there. I have a question about this algorithm. It lists every permutation of an array.
[ 'a', 'b', 'c', 'd' ]
[ 'b', 'a', 'c', 'd' ]
[ 'c', 'a', 'b', 'd' ]
[ 'a', 'c', 'b', 'd' ]
[ 'b', 'c', 'a', 'd' ]
etc...
I was wondering if anyone could tell me a way to modify this algorithm so that it gives every permutation of length n from an array of letters.
For example if n is 2:
['a', 'b']
['a', 'c']
['a', 'd']
etc...
Thank you for taking the time to read my question. Any help much appreciated.