Permutations in JavaScript?

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

    Little late, but like to add a slightly more elegant version here. Can be any array...

    function permutator(inputArr) {
      var results = [];
    
      function permute(arr, memo) {
        var cur, memo = memo || [];
    
        for (var i = 0; i < arr.length; i++) {
          cur = arr.splice(i, 1);
          if (arr.length === 0) {
            results.push(memo.concat(cur));
          }
          permute(arr.slice(), memo.concat(cur));
          arr.splice(i, 0, cur[0]);
        }
    
        return results;
      }
    
      return permute(inputArr);
    }
    

    Adding an ES6 (2015) version. Also does not mutate the original input array. Works in the console in Chrome...

    const permutator = (inputArr) => {
      let result = [];
    
      const permute = (arr, m = []) => {
        if (arr.length === 0) {
          result.push(m)
        } else {
          for (let i = 0; i < arr.length; i++) {
            let curr = arr.slice();
            let next = curr.splice(i, 1);
            permute(curr.slice(), m.concat(next))
         }
       }
     }
    
     permute(inputArr)
    
     return result;
    }
    

    So...

    permutator(['c','a','t']);
    

    Yields...

    [ [ 'c', 'a', 't' ],
      [ 'c', 't', 'a' ],
      [ 'a', 'c', 't' ],
      [ 'a', 't', 'c' ],
      [ 't', 'c', 'a' ],
      [ 't', 'a', 'c' ] ]
    

    And...

    permutator([1,2,3]);
    

    Yields...

    [ [ 1, 2, 3 ],
      [ 1, 3, 2 ],
      [ 2, 1, 3 ],
      [ 2, 3, 1 ],
      [ 3, 1, 2 ],
      [ 3, 2, 1 ] ]
    

提交回复
热议问题