Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Combinations

Status
Not open for further replies.

cpmasesa

Programmer
Oct 24, 2002
78
AE
Hello,

I need to generate a list of all the possible combinations of 6 letter 'words' from a list of 20 letters.

This should give a total of 27,907,200 'words'! (20 * 19 * 18 * 17 * 16 * 15)

Could some one help me with a code snippet that would generate all the possible combinations?

Or point me to where i can get information on how to go about doing that.

TIA

cpmasesa
 
This is really a question about algorithms and not about Delphi. However, it is not too difficult to produce all the combinations of 6 letter words from 20 letters.

I am assuming that some of the 20 letters will be the same which if they are chosen randomly will almost certainly be the case.

I'm assuming that you want to end up with a stringlist containing the of 27,907,200 words. This may not actually be possible in practice - but it shows the algorithm.

Step 1. Put the 20 letters into a string called Letters.

Step 2. Create the stringlist called Words. Ensure that sorted is set to true and that duplicates are ignored.

Step 3. Create a string variable called Temp. Set it to '123456'.

Step 4. Create 6 integer variables a, b, c, d, e, f which will be used as subscripts into Letters.

Step 5. This consists of six nested FOR loops. One loop for each of the variables a, b, c, d, e, f.
Code:
FOR a := 1 to 20 do begin
 Temp[1] := Letters[a];
 For b := 1 to 20 do begin
  if b<>a then begin
   Temp[2] := Letters[b];
   For c := 1 to 20 do begin
    if (c<>a) and (c<>b) then begin 
     Temp[3] := Letters[c];
     For d := 1 to 20 do begin
      if (d<>a) and (d<>b) and (d<>c) then begin 
       Temp[4] := Letters[d];
       For e := 1 to 20 do begin
        if (e<>a) and (e<>b) and (e<>c) and (e<>d) then begin
         Temp[5] := Letters[e];
         For f := 1 to 20 do begin
          if (f<>a) and (f<>b) and (f<>c) and (f<>d) and (f<>e) then begin
           Temp[6] := Letters[f];
           Words.Add ( Temp );

// ....you can supply all the 'end' statements!

Of course the code could be more elegant. E.g. the FOR loops should be:
Code:
for x := Low(Letters) to High(Letters).
You will probably want to write the temp variable to a file instead of adding it to a stringlist. At the very least you will want to save the stringlist to a file. Note that the file will be quite large - about 200 MB.



Andrew
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top