Permutations via Heap's algorithm with a mystery comma

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

    I'm sharing this answer because I want to show how a narrow set of features in old javascript can be concise and clear as well. It is sometimes an advantage to write code that runs in the oldest of javascript engines and ports easily to other languages like C. Using a callback in this case works well because it makes the function available to a wider array of uses such as reducing a large set of permutations to a unique set as they are created.

    Very short variable names can make the algorithm more clear.

    function swap(a, i, j) { var t = a[i]; a[i] = a[j]; a[j] = t }
    function perm(arr, n, cb) {
      if (n === 1) {
        cb(arr);
      } else {
        for (var i = 0; i < n; i++) {
          perm(arr, n - 1, cb);
          swap(arr, n % 2 ? 0 : i, n - 1);
        }
      }
    }
    
    perm([1, 2, 3, 4], 4, function(p) {
      console.log(p);
    })

    This is a useful function for testing, so I made this available to the data-driven test kit I use:

    https://github.com/quicbit-js/test-kit#tpermut-

提交回复
热议问题