Heap's Permute

[Home]   [Puzzles & Projects]    [Delphi Techniques]   [Math topics]   [Library]   [Utilities]




Search WWW

Search DelphiForFun.org

As of October, 2016, Embarcadero is offering a free release of Delphi (Delphi 10.1 Berlin Starter Edition ).     There are a few restrictions, but it is a welcome step toward making more programmers aware of the joys of Delphi.  They do say "Offer may be withdrawn at any time", so don't delay if you want to check it out.  Please use the feedback link to let me know if the link stops working.


Support DFF - Shop

 If you shop at Amazon anyway,  consider using this link. 


We receive a few cents from each purchase.  Thanks


Support DFF - Donate

 If you benefit from the website,  in terms of knowledge, entertainment value, or something otherwise useful, consider making a donation via PayPal  to help defray the costs.  (No PayPal account necessary to donate via credit card.)  Transaction is secure.

Mensa Daily Puzzlers

For over 15 years Mensa Page-A-Day calendars have provided several puzzles a year for my programming pleasure.  Coding "solvers" is most fun, but many programs also allow user solving, convenient for "fill in the blanks" type.  Below are Amazon  links to the two most recent years.

Mensa 365 Puzzlers  Calendar 2017

Mensa 365 Puzzlers Calendar 2018

(Hint: If you can wait, current year calendars are usually on sale in January.)


Feedback:  Send an e-mail with your comments about this program (or anything else).

Search DelphiForFun.org only




Problem Description

Here's an algorithm developed by J.R. Heap in 1963 which generates permutations of data items. It is quite efficient because it swaps only 2 elements for each one generated. The disadvantage may be that that there is no apparent order in the generated permutations.  Search "Heap's algorithm" on Wikipedia for more information.

Background & Techniques

Our DelphiforFun website has a "UCombosV2" unit which generates many kinds of permutations and combinations, but I needed one that was easy to code for another "start from scratch" project.   The Wikipedia article has "pseudocode" for both recursive and non-recursive implementations of the algorithm. This demo has two Delphi versions of each; one with inputs as an array of characters and the other a string of characters. The four versions  are PermuteCharArray_R, PermuteString_R, PermuteCharArray_NR, and PermuteStringArray_NR.

All four routines run about the same speed generating the 3.6 million permutations of 10 characters in less than 200 milliseconds. Checking the "Display" box increases the run time considerably!  Permuting 11 character will take 11 times longer.  Try more than 12 and you're on your own!

Non-programmers are welcome to read on, but may want to jump to bottom of this page to download the executable program now.

Programmer's Notes

Here is the pseudo code for the recursive version of the algorithm:

procedure generate(n : integer, A : array of any):
if n = 1 then
  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

The character Delphi version is  pretty direct translation of the pseudo code.

bulletThe  "generate" procedure name became Permute_R
bullet"Output(A)" became a call to a user routine PermuteCallBack with permuted character passed as a string.
bulletA short "Swap" procedure was implemented to swap tw passed characters.

I believe that was about it.  Recursion (a subroutine calling itself) in general seems like magic.  As you tell from the pseudo code examples, it does simpliy implementation in case when the basic procedure must be invoked multiple times to compute the "next" entry.  Th simplest example is the recursive routine for computing  the "factorial" of an integer.  Denoted  as   N!, the factorial is the product of all integers 1 through N. Here's the routine:

function factorial(N:integer):integer;
begin If N>1 then result:=N*factorial(N-1) else result:=1; end;

You can uncomment the Showmessage statement in the program's FormCreate procedure to prove that it works!

One other Delphi feature used here is the ability to of the define multiple versions of a routine with the same name just so long as the parameter lists are unique.  Add the statement Overload after the initial  definition line and  Delphi will figure out which one based on the parameter list.  You'll see it used several times in this program to handle "string" and "Character array" versions performing the same task with the same routine name.

A late addition is a VerboseBox check box to to display the pair of characters swapped for each permutation generated.  Examining the output shows that the program works from left to right generating all permutations of the first 2, then 3 then 4 characters, etc.  In the default ABCD example, the 1st six have all permutations of ABC, the 2nd six have all for ABD, etc.   

Running/Exploring the Program 

bulletDownload  executable
bulletDownload source 

Suggestions for Further Explorations

Could similar version be created that generates permutations for all K of N items?
.This algorithm seems quite fast.  I wonder how it compares with other alternatives (including mine).
If the input characters include duplicates, the permutations generated will also contain duplicates.  ANy good way to add a filter fir this case?


Original:  April 21, 2017

Modified:  May 15, 2018

  [Feedback]   [Newsletters (subscribe/view)] [About me]
Copyright 2000-2018, Gary Darby    All rights reserved.