Permutations in JavaScript?

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

    Here is another "more recursive" solution.

    function perms(input) {
      var data = input.slice();
      var permutations = [];
      var n = data.length;
    
      if (n === 0) {
        return [
          []
        ];
      } else {
        var first = data.shift();
        var words = perms(data);
        words.forEach(function(word) {
          for (var i = 0; i < n; ++i) {
            var tmp = word.slice();
            tmp.splice(i, 0, first)
            permutations.push(tmp);
          }
        });
      }
    
      return permutations;
    }
    
    var str = 'ABC';
    var chars = str.split('');
    var result = perms(chars).map(function(p) {
      return p.join('');
    });
    
    console.log(result);

    Output:

    [ 'ABC', 'BAC', 'BCA', 'ACB', 'CAB', 'CBA' ]
    

提交回复
热议问题