A
A
Alex2015-11-04 00:01:26
JavaScript
Alex, 2015-11-04 00:01:26

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, 4231etc.
How to iterate over all possible combinations?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nirvimel, 2015-11-04
@nirvimel

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])));

Not mine, of course. Just get out of here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question