Permutations in JavaScript?

前端 未结 30 2687
不思量自难忘°
不思量自难忘° 2020-11-21 06:52

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 possib
30条回答
  •  不知归路
    2020-11-21 07:06

    I have improved SiGanteng's answer.

    Now it is possible to call permute more than once, because permArr and usedChars are cleared each time.

    function permute(input) {
        var permArr = [],
            usedChars = [];
        return (function main() {
            for (var i = 0; i < input.length; i++) {
                var ch = input.splice(i, 1)[0];
                usedChars.push(ch);
                if (input.length == 0) {
                    permArr.push(usedChars.slice());
                }
                main();
                input.splice(i, 0, ch);
                usedChars.pop();
            }
            return permArr;
        })();
    }
    

    function permute(input) {
      var permArr = [],
          usedChars = [];
      return (function main() {
        for (var i = 0; i < input.length; i++) {
          var ch = input.splice(i, 1)[0];
          usedChars.push(ch);
          if (input.length == 0) {
            permArr.push(usedChars.slice());
          }
          main();
          input.splice(i, 0, ch);
          usedChars.pop();
        }
        return permArr;
      })();
    }
    document.write(JSON.stringify(permute([5, 3, 7, 1])));

提交回复
热议问题