Permutations in JavaScript?

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

    My first contribution to the site. Also, according to the tests that I have done, this code runs faster than all the other methods mentioned here before this date, of course it is minimal if there are few values, but the time increases exponentially when adding too many.

    function permutations(arr) {
        var finalArr = [];
        function iterator(arrayTaken, tree) {
            var temp;
            for (var i = 0; i < tree; i++) {
                temp = arrayTaken.slice();
                temp.splice(tree - 1 - i, 0, temp.splice(tree - 1, 1)[0]);
                if (tree >= arr.length) {
                    finalArr.push(temp);
                } else {
                    iterator(temp, tree + 1);
                }
            }
        }
        iterator(arr, 1);
        return finalArr;
    };
    
    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2020-11-21 07:13

    Here's one I made...

    const permute = (ar) =>
      ar.length === 1 ? ar : ar.reduce( (ac,_,i) =>
        {permute([...ar.slice(0,i),...ar.slice(i+1)]).map(v=>ac.push([].concat(ar[i],v))); return ac;},[]);
    

    And here it is again but written less tersely!...

    function permute(inputArray) {
      if (inputArray.length === 1) return inputArray;
      return inputArray.reduce( function(accumulator,_,index){
        permute([...inputArray.slice(0,index),...inputArray.slice(index+1)])
          .map(value=>accumulator.push([].concat(inputArray[index],value)));
        return accumulator;
      },[]);
    }
    

    How it works: If the array is longer than one element it steps through each element and concatenates it with a recursive call to itself with the remaining elements as it's argument. It doesn't mutate the original array.

    0 讨论(0)
  • 2020-11-21 07:13

    Quite late. Still just in case if this helps anyone.

    function permute(arr) {
      if (arr.length == 1) return arr
    
      let res = arr.map((d, i) => permute([...arr.slice(0, i),...arr.slice(i + 1)])
                                  .map(v => [d,v].join(''))).flat()
    
      return res
    }
    
    console.log(permute([1,2,3,4]))

    0 讨论(0)
  • 2020-11-21 07:14
    var inputArray = [1, 2, 3];
    
    var result = inputArray.reduce(function permute(res, item, key, arr) {
        return res.concat(arr.length > 1 && arr.slice(0, key).concat(arr.slice(key + 1)).reduce(permute, []).map(function(perm) { return [item].concat(perm); }) || item);
    }, []);
    
    
    alert(JSON.stringify(result));
    
    0 讨论(0)
  • 2020-11-21 07:14
       function perm(xs) {
           return xs.length === 0 ? [[]] : perm(xs.slice(1)).reduce(function (acc, ys) {
            for (var i = 0; i < xs.length; i++) {
              acc.push([].concat(ys.slice(0, i), xs[0], ys.slice(i)));
            }
            return acc;
          }, []);
        }
    

    Test it with:

    console.log(JSON.stringify(perm([1, 2, 3,4])));
    
    0 讨论(0)
提交回复
热议问题