Multiple permutations with head algorithm

53 Views Asked by At

Have written the following elisp function to compute permutations of a string using hde Heap Algarithm. But I am getting repetitions, whereas the algorithm should avoid this.

(defun permute-strg-heap (strg h &optional result)
  "Generate all permutations of string STRG using recursive
backtracking."

  (if (null result) (setq result '()))

  (if (= h 1)

      (progn
        (push (copy-sequence strg) result)  ; Output the permutation
        (message "%s" strg))

    (progn

      (setq result
        (permute-strg-heap strg (1- h) result))

      ;; Generate permutations for i-th swapped with each i-1 initial
      (let ( (j 0) )
        (while (< j h)

          ;; Swap choice based upon h (even or odd)
          (if (evenp h)
              (swap-chars strg j (1- h))
            (swap-chars strg 0 (1- h)))

          (setq result
            (permute-strg-heap strg (1- h) result))

          (setq j (1+ j))) )))

  result)

This should be the algorithm to implement

procedure generate(k : integer, A : array of any):
    if k = 1 then
        output(A)
    else
        // Generate permutations with k-th unaltered
        // Initially k = length(A)
        generate(k - 1, A)

        // Generate permutations for k-th swapped with each k-1 initial
        for i := 0; i < k-1; i += 1 do
            // Swap choice dependent on parity of k (even or odd)
            if k is even then
                swap(A[i], A[k-1]) // zero-indexed, the k-th is at k-1
            else
                swap(A[0], A[k-1])
            end if
            generate(k - 1, A)
        end for
    end if
0

There are 0 best solutions below