简体   繁体   English

Javascript 中的堆算法又名所有排列

[英]Heap's algorithm in Javascript a.k.a. all permutations

Goal:目标:

I want to execute a specific function for every permutation of an array .我想为数组的每个排列执行特定的 function。 I don't need to save intermediate permutations.我不需要保存中间排列。

Paraphrase:释义:

I'm searching for a Javascript implementation of Heap's algorithm , that calls a function for each permutation我正在搜索堆算法的 Javascript 实现,它为每个排列调用 function

Taken from here: https://en.wikipedia.org/wiki/Heap%27s_algorithm取自这里: 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;
      }
  }
}

You could call it like你可以这样称呼它

permute ([1,2,3], function (array){
   document.write (JSON.stringify (array) + " ; ");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM