Permutations in JavaScript?

前端 未结 30 2637
不思量自难忘°
不思量自难忘° 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:29

    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

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

提交回复
热议问题