Shuffle an array as many as possible

前端 未结 8 1369
一向
一向 2020-12-07 05:21

I have an array like this

[0,2,3]

The possible shuffling of this array are

[0,2,3], [2,3,0], [3,0,2], [3,2,0], [0,3,2],         


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 05:46

    The first thing to note is that the number of permutations increases very fast with regard to the number of elements (13 elements = 6 bilion permutations), so any kind of algorithm that generates them will deteriorate in performance for a large enough input array.

    The second thing to note is that since the number of permutations is very large, storing them in memory is expensive, so you're way better off using a generator for your permutations and doing stuff with them as they are generated.

    The third thing to note is that recursive algorithms bring a large overhead, so even if you find a recursive solution, you should strive to get a non-recursive one. Obtaining a non-recursive solution if a recursive one exists is always possible, but it may increase the complexity of the code.

    I have written a non recursive implementation for you, based on the Steinhaus–Johnson–Trotter algorithm (http://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm)

    function swap(arr, a,b){
      var temp = arr[a];
      arr[a]=arr[b];
      arr[b]=temp;
    }
    
    function factorial(n) {
      var val = 1;
      for (var i=1; i=0; i+=inc) {
          func.call(perm);
          swap (perm, i, i+1);
        }  
    
        func.call(perm);
    
        if (inc === 1) {
          swap(perm, 0,1);
        } else {
          swap(perm, perm.length-1, perm.length-2);
        }
      }
    }
    
    console.clear();
    
    count = 0;
    permute([1,2,3,4,5,6], function(){console.log(this); count++;});
    
    console.log('There have been ' + count + ' permutations');
    

    http://jsbin.com/eXefawe/2/edit

提交回复
热议问题