0

目标:

我想为array 的每个排列执行一个特定的函数。我不需要保存中间排列。

释义:

我正在寻找堆算法的 Javascript 实现,它为每个排列调用一个函数

4

1 回答 1

1

取自这里:https ://en.wikipedia.org/wiki/Heap%27s_algorithm

/**
 * @brief : Heap's algorithm for permutating an array
 * @param callbackFunction: this function gets called for each permutation
 * @return : void
 * @props : This code is based on the algorithm stated on https://en.wikipedia.org/wiki/Heap%27s_algorithm
 **/
function permute(inputArr, callbackFunction) {
  function swap(array, index1, index2){
    let tmp = array[index1];
    array[index1] = array[index2];
    array[index2] = tmp;
  }
  let array = inputArr;
  let n = array.length;
  //c is an encoding of the stack state. c[k] encodes the for-loop counter for when generate(k+1, array) is called
  let c = Array(n);

  for (let i = 0; i < n; i += 1){
      c[i] = 0;
  }

  callbackFunction(array);

  //i acts similarly to the stack pointer
  let i = 0;
  while (i < n) {
      if (c[i] < i) {
          if (i % 2 == 0) {
              swap(array, 0, i);
          } else {
              swap(array, c[i], i);
          }

          callbackFunction(array);

          //Swap has occurred ending the for-loop. Simulate the increment of the for-loop counter
          c[i] += 1;
          //Simulate recursive call reaching the base case by bringing the pointer to the base case analog in the array
          i = 0;
      } else {
          //Calling generate(i+1, array) has ended as the for-loop terminated. Reset the state and simulate popping the stack by incrementing the pointer.
          c[i] = 0;
          i += 1;
      }
  }
}

你可以这样称呼它

permute ([1,2,3], function (array){
   document.write (JSON.stringify (array) + " ; ");
}
于 2020-07-29T13:36:23.667 回答