Permutations via Heap's algorithm with a mystery comma

前端 未结 3 1695
野的像风
野的像风 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:57

    Updated answer since Jan-2018: The accepted answer is absolutely correct, but js has evolved since then. And with it comes some new features, 2 of which could help this answer.

    Array destructuring:

    let [a, b] = [1, 2]; // a=1, b=2
    

    Generators:

    function *foo {
      yield 1;
      yield 2;
      yield 3;
    }
    const bar = foo();
    bar.next(); // 1
    bar.next(); // 2
    bar.next(); // 3
    

    With this we can implement the Heap's algorithm like this:

    function *heaps(arr, n) {
      if (n === undefined) n = arr.length;
      if (n <= 1) yield arr;
      else {
        for (let i = 0; i < n - 1; i++) {
          yield *heaps(arr, n-1);
          if (n % 2 === 0) [arr[n-1], arr[i]] = [arr[i], arr[n-1]];
          else             [arr[n-1], arr[0]] = [arr[0], arr[n-1]];
        }
        yield *heaps(arr, n-1);
      }
    }
    
    
    for (let a of heaps([1, 2, 3, 4])) {
      console.log(`[${a.join(', ')}]`);
    }
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题