0

I'm wanting to generate all possible permutations of the letters A - G (seven) and Heap's algorithm allegedly makes this possible.

However, when I look at the pseudo code from the Wikipedia page I see this:

procedure generate(n : integer, A : array of any):
    if n = 1 then
          output(A)
    else
        for i := 0; i < n - 1; i += 1 do
            generate(n - 1, A)
            if n is even then
                swap(A[i], A[n-1])
            else
                swap(A[0], A[n-1])
            end if
        end for
        generate(n - 1, A)
    end if

....and have no idea what it means.

So, I know that if I have seven letters (A-G) it'll apperently find all the possible permutations of the first six letters while the letter at the end stays the same.

Meaning, it'll find all possible permuations of A-F while G is on the end, and do that until each letter has been on the end.

Given, I have seven letters, that means "N" is odd, and thus I always switch the end letter (seventh one) with the letter that is in the first slot.

But (and I know this isn't how it works, but it's all I'm getting from it) won't that just result in the same two letters being swapped constantly and no diffent permutations?

I've scoured google results for the past 4 hours and can't find anything that explains line by line the above pseudo-code.

Help is greatly appreciated!!

9
  • do you have any javascript code to share? Commented Nov 8, 2016 at 2:25
  • 1
    Because the code calls generate before it does the swap, the letter in A[0] is not constant. Evidently, when n is odd, the letter at A[0] goes through all possibilities, whereas when n is even, you need to take the letter at A[i] to get all of the possibilities. Not sure how Heap proved that works for all values of n. Commented Nov 8, 2016 at 2:52
  • There's a diagram on the wikipedia page that shows all the swaps. Commented Nov 8, 2016 at 2:55
  • @user3386109 what exactly does generate mean/do in this context? Commented Nov 8, 2016 at 5:39
  • @JaromandaX No, I'm just wanting to understand the pseudo code so that I can use it later in javascript. Commented Nov 8, 2016 at 5:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.