Generating letter combinations -- please help

  • Thread starter Thread starter almurph
  • Start date Start date
A

almurph

Hi,

I'm trying to enumerate all possible permutations of the first 13-
letter of the alphabet in groups of 5. So that's 13^5 combinations or
371,293. The order is unimportant but all patterns should be unique.

For example:

AAAAA
ABAAA
ACAAA
etc...


Problem is though, I'm having difficulty developing a strategy for
complete population. Can any one help me out please. Any suggestions/
ideas/comments/code-samples/ much appreciated.

Thanking you,
Al.
 
I haven't let it run to completion, but how about below; it uses a
char[] rather than lots of strings to save the GC some work... it only
goes 5 levels deep on the stack, so shouldn't blow up...

Marc

static void Main()
{
char[] data = new char[5];
Loop(data, 0);
Console.WriteLine(count);
}
static int count;
static void Loop(char[] buffer, int level)
{
int nextLevel = level + 1;
for (char c = 'A'; c < 'Z'; c++)
{
buffer[level] = c;
if (nextLevel == buffer.Length)
{
Console.WriteLine(buffer);
count++;
}
else
{
Loop(buffer, nextLevel);
}
}
}
 
I haven't let it run to completion, but how about below; it uses a
char[] rather than lots of strings to save the GC some work... it only
goes 5 levels deep on the stack, so shouldn't blow up...

Marc

        static void Main()
        {
            char[] data = new char[5];
            Loop(data, 0);
            Console.WriteLine(count);
        }
        static int count;
        static void Loop(char[] buffer, int level)
        {
            int nextLevel = level + 1;
            for (char c = 'A'; c < 'Z'; c++)
            {
                buffer[level] = c;
                if (nextLevel == buffer.Length)
                {
                    Console.WriteLine(buffer);
                    count++;
                }
                else
                {
                    Loop(buffer, nextLevel);
                }
            }
        }

Marc,

This is tight but I like it. Yes, it works. I also added a
container to it (like a hastable ot arraylist to store the
enumeration). Say, if you had a array of chars say char[] myChars =
{'A', 'C', 'E', 'X', 'Y'}
or something liek that - do you think it possible to cycle through
them and not all the letters in the alphabet?

PS: Small issue, I changed:

for (char c = 'A'; c < 'Z'; c++)

to

for (char c = 'A'; c <= 'Z'; c++)
 
Back
Top