Permutations via Heap's algorithm with a mystery comma

前端 未结 3 1741
野的像风
野的像风 2021-02-08 15:23

I have spent the whole day (finally) wrapping my head around a permutation algorithm in practice for an admissions application on Friday. Heap\'s algorithm seemed most simple an

3条回答
  •  轮回少年
    2021-02-08 15:54

    The problem, besides using index n where you should be using n - 1 is that you assume the array must be copied between calls (i.e. immutable behaviour).

    The algorithm assumes that the array is always the same in each recursive step, so thanks to how JavaScript handles scope you can greatly simplify the code:

    function permutationArr(num) 
    { 
      var arr = (num + '').split(''),
      permutations = [];   
    
      function swap(a, b)
      {
        var tmp = arr[a];
        arr[a] = arr[b];
        arr[b] = tmp;
      }
    
      function generate(n) {
        if (n == 1) {
          permutations.push(arr.join());
        } else {
          for (var i = 0; i != n; ++i) {
            generate(n - 1);
            swap(n % 2 ? 0 : i, n - 1);
          }
        }
      }
    
      generate(arr.length);
      return permutations;
    }    
    
    console.log(permutationArr(1234)); 

    Output

    ["1,2,3,4", "2,1,3,4", "3,1,2,4", "1,3,2,4", "2,3,1,4", "3,2,1,4", "4,2,3,1",
     "2,4,3,1", "3,4,2,1", "4,3,2,1", "2,3,4,1", "3,2,4,1", "4,1,3,2", "1,4,3,2", 
     "3,4,1,2", "4,3,1,2", "1,3,4,2", "3,1,4,2", "4,1,2,3", "1,4,2,3", "2,4,1,3", 
     "4,2,1,3", "1,2,4,3", "2,1,4,3"]
    

提交回复
热议问题