Answer the question
In order to leave comments, you need to log in
How to iterate over all possible combinations of digits in a number?
There is some number 1234
.
Task: find and execute a certain code with all possible variations of the digits in a given number: 1243
, 1432
, 4231
etc.
How to iterate over all possible combinations?
Answer the question
In order to leave comments, you need to log in
var permArr = [],
usedChars = [];
function permute(input) {
var i, ch;
for (i = 0; i < input.length; i++) {
ch = input.splice(i, 1)[0];
usedChars.push(ch);
if (input.length == 0) {
permArr.push(usedChars.slice());
}
permute(input);
input.splice(i, 0, ch);
usedChars.pop();
}
return permArr
};
document.write(JSON.stringify(permute([5, 3, 7, 1])));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question