Print all permutations of a specified set of characters for a given length when repetition is allowed

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] charArray = { 'a', 'b', 'c', 'd' };
            int numberOfSlots = 3;
            int[] numArray = new int[numberOfSlots];
            printString(charArray, numArray, 0);
        }
        
        public static void printString(char[] charArray, int[] numArray, int depth)
        {
            if (depth == numArray.Length)
            {
                //print the array
                for (int i = 0; i < numArray.Length; i++)
                {
                    Console.Write(charArray[numArray[i]].ToString());
                }
                Console.WriteLine();
                return;
            }
            else
            {
                for (int i = 0; i < charArray.Length; i++)
                {
                    numArray[depth] = i;
                    printString(charArray, numArray, depth + 1);
                }
            }
        }
    }
}

Output
======
aaa
aab
aac
aad
aba
abb
abc
abd
aca
acb
acc
acd
ada
adb
adc
add
baa
bab
bac
bad
bba
bbb
bbc
bbd
bca
bcb
bcc
bcd
bda
bdb
bdc
bdd
caa
cab
cac
cad
cba
cbb
cbc
cbd
cca
ccb
ccc
ccd
cda
cdb
cdc
cdd
daa
dab
dac
dad
dba
dbb
dbc
dbd
dca
dcb
dcc
dcd
dda
ddb
ddc
ddd
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s