Javascript中的堆算法a.k.a. all permutations

Posted

技术标签:

【中文标题】Javascript中的堆算法a.k.a. all permutations【英文标题】:Heap's algorithm in Javascript a.k.a. all permutations 【发布时间】:2020-11-19 02:51:46 【问题描述】:

目标:

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

释义:

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

【问题讨论】:

【参考方案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) + " ; ");

【讨论】:

以上是关于Javascript中的堆算法a.k.a. all permutations的主要内容,如果未能解决你的问题,请参考以下文章

算法系列之--Javascript和Kotlin的堆排序算法(原)

JavaScript中的堆和栈

C++分段错误中的堆算法

理解JavaScript中的堆和栈

UVa11988 Broken Keyboard (a.k.a. Beiju Text) (链表)

浅析STL算法中的堆排序