Permutations in JavaScript?

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

    The following function permutates an array of any type and calls a specified callback function on each permutation found:

    /*
      Permutate the elements in the specified array by swapping them
      in-place and calling the specified callback function on the array
      for each permutation.
    
      Return the number of permutations.
    
      If array is undefined, null or empty, return 0.
    
      NOTE: when permutation succeeds, the array should be in the original state
      on exit!
    */
      function permutate(array, callback) {
        // Do the actual permuation work on array[], starting at index
        function p(array, index, callback) {
          // Swap elements i1 and i2 in array a[]
          function swap(a, i1, i2) {
            var t = a[i1];
            a[i1] = a[i2];
            a[i2] = t;
          }
    
          if (index == array.length - 1) {
            callback(array);
            return 1;
          } else {
            var count = p(array, index + 1, callback);
            for (var i = index + 1; i < array.length; i++) {
              swap(array, i, index);
              count += p(array, index + 1, callback);
              swap(array, i, index);
            }
            return count;
          }
        }
    
        if (!array || array.length == 0) {
          return 0;
        }
        return p(array, 0, callback);
      }
    

    If you call it like this:

      // Empty array to hold results
      var result = [];
      // Permutate [1, 2, 3], pushing every permutation onto result[]
      permutate([1, 2, 3], function (a) {
        // Create a copy of a[] and add that to result[]
        result.push(a.slice(0));
      });
      // Show result[]
      document.write(result);
    

    I think it will do exactly what you need - fill an array called result with the permutations of the array [1, 2, 3]. The result is:

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

    Slightly clearer code on JSFiddle: http://jsfiddle.net/MgmMg/6/

提交回复
热议问题