[JavaScript] JavaScript实现数组全排列代码 →→→→→进入此内容的聊天室

来自 , 2021-01-21, 写在 JavaScript, 查看 157 次.
URL http://www.code666.cn/view/741a0099
  1. /*
  2.   Permutate the elements in the specified array by swapping them
  3.   in-place and calling the specified callback function on the array
  4.   for each permutation.
  5.  
  6.   Return the number of permutations.
  7.  
  8.   If array is undefined, null or empty, return 0.
  9.  
  10.   NOTE: when permutation succeeds, the array should be in the original state
  11.   on exit!
  12.  
  13.   code from http://www.sharejs.com/codes/
  14. */
  15.   function permutate(array, callback) {
  16.     // Do the actual permuation work on array[], starting at index
  17.     function p(array, index, callback) {
  18.       // Swap elements i1 and i2 in array a[]
  19.       function swap(a, i1, i2) {
  20.         var t = a[i1];
  21.         a[i1] = a[i2];
  22.         a[i2] = t;
  23.       }
  24.  
  25.       if (index == array.length - 1) {
  26.         callback(array);
  27.         return 1;
  28.       } else {
  29.         var count = p(array, index + 1, callback);
  30.         for (var i = index + 1; i < array.length; i++) {
  31.           swap(array, i, index);
  32.           count += p(array, index + 1, callback);
  33.           swap(array, i, index);
  34.         }
  35.         return count;
  36.       }
  37.     }
  38.  
  39.     if (!array || array.length == 0) {
  40.       return 0;
  41.     }
  42.     return p(array, 0, callback);
  43.   }
  44.  
  45.  
  46. //javascript/8711

回复 "JavaScript实现数组全排列代码"

这儿你可以回复上面这条便签

captcha