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
Similar in spirit to the Haskell-style solution by @crl, but working with
reduce
:Answer without the need for a exterior array or additional function
This is an interesting task and and here is my contribution. It's very simple and fast. If interested please bear with me and read on.
If you would like to this job fast, you definitely have to get yourself into dynamical programming. Which means you should forget about recursive approaches. That's for sure...
OK le_m's code which uses the Heap's method seems to be the fastest so far. Well i haven't got a name for my algorithm, i don't know if it's already been implemented or not but it's very simple and fast. As with all dynamical programming approaches we will start with the simplest problem and go for the final result.
Assuming that we have an array of
a = [1,2,3]
we will start withThen follow these three steps;
r
(result) array we will add the next item of the input array.t
. (well except for the first one not to waste time with 0 rotation)r
the interim arrayt
should hold the next level of results so we maker = t; t = [];
and carry on up until the length of the input arraya
.So the following are our steps;
So here is the code
In multiple test i have seen it resolving the 120 permutations of [0,1,2,3,4] for 2000 times in 25~35ms.
The following very efficient algorithm uses Heap's method to generate all permutations of N elements with runtime complexity in O(N!):
The same algorithm implemented as a generator with space complexity in O(N):
Performance comparison
Feel free to add your implementation to the following benchmark.js test suite:
Run-time results for Chrome 48:
This is a very nice use-case for map/reduce:
[].concat(cv,a)