Permutations in JavaScript?

前端 未结 30 2741
不思量自难忘°
不思量自难忘° 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条回答
  •  旧时难觅i
    2020-11-21 07:22

    Most answers to this question use expensive operations like continuous insertions and deletions of items in an array, or copying arrays reiteratively.

    Instead, this is the typical backtracking solution:

    function permute(arr) {
      var results = [],
          l = arr.length,
          used = Array(l), // Array of bools. Keeps track of used items
          data = Array(l); // Stores items of the current permutation
      (function backtracking(pos) {
        if(pos == l) return results.push(data.slice());
        for(var i=0; i
    permute([1,2,3,4]); // [  [1,2,3,4], [1,2,4,3], /* ... , */ [4,3,2,1]  ]
    

    Since the results array will be huge, it might be a good idea to iterate the results one by one instead of allocating all the data simultaneously. In ES6, this can be done with generators:

    function permute(arr) {
      var l = arr.length,
          used = Array(l),
          data = Array(l);
      return function* backtracking(pos) {
        if(pos == l) yield data.slice();
        else for(var i=0; i
    var p = permute([1,2,3,4]);
    p.next(); // {value: [1,2,3,4], done: false}
    p.next(); // {value: [1,2,4,3], done: false}
    // ...
    p.next(); // {value: [4,3,2,1], done: false}
    p.next(); // {value: undefined, done: true}
    

提交回复
热议问题