Permutations in JavaScript?

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

    Answer without the need for a exterior array or additional function

    function permutator (arr) {
      var permutations = [];
      if (arr.length === 1) {
        return [ arr ];
      }
    
      for (var i = 0; i <  arr.length; i++) { 
        var subPerms = permutator(arr.slice(0, i).concat(arr.slice(i + 1)));
        for (var j = 0; j < subPerms.length; j++) {
          subPerms[j].unshift(arr[i]);
          permutations.push(subPerms[j]);
        }
      }
      return permutations;
    }
    

提交回复
热议问题