I'm trying to write a function that does the following:
- takes an array of integers as an argument (e.g. [1,2,3,4])
- creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4
the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string
I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...)
var permArr = [], usedChars = [];
function permute(input) {
var i, ch, chars = input.split("");
for (i = 0; i < chars.length; i++) {
ch = chars.splice(i, 1);
usedChars.push(ch);
if (chars.length == 0)
permArr[permArr.length] = usedChars.join("");
permute(chars.join(""));
chars.splice(i, 0, ch);
usedChars.pop();
}
return permArr
};
Note: I'm looking to make the function return arrays of integers, not an array of strings.
I really need the solution to be in JavaScript. I've already figured out how to do this in python
Most answers to this question use expensive operations like continuous insertions and deletions of items in an array, or copying arrays reiteratively.
Instead, this is the typical backtracking solution:
Since the results array will be huge, it might be a good idea to iterate the results one by one instead of allocating all the data simultaneously. In ES6, this can be done with generators:
Result:
Little late, but like to add a slightly more elegant version here. Can be any array...
Adding an ES6 (2015) version. Also does not mutate the original input array. Works in the console in Chrome...
So...
Yields...
And...
Yields...
The following function permutates an array of any type and calls a specified callback function on each permutation found:
If you call it like this:
I think it will do exactly what you need - fill an array called
result
with the permutations of the array [1, 2, 3]. The result is:Slightly clearer code on JSFiddle: http://jsfiddle.net/MgmMg/6/
Here's a very short solution, that only works for 1 or 2 long strings. It's a oneliner, and it's blazing fast, using ES6 and not depending on jQuery. Enjoy: