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
I have improved SiGanteng's answer.
Now it is possible to call
permute
more than once, becausepermArr
andusedChars
are cleared each time.If you notice, the code actually splits the chars into an array prior to do any permutation, so you simply remove the join and split operation
Here is a minimal ES6 version. The flatten and without functions can be pulled from Lodash.
Result:
// sample execution //for more details refer this link
// http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
Outputs lexicographically ordered permutations. Works only with numbers. In other case, you have to change the swap method on line 34.