Print all permutations of a specified set of characters for a given length without repetition

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] charArray = { 'a', 'b', 'c', 'd' };
            int numberOfSlots = 4;
            int[] numArray = new int[numberOfSlots];
            ArrayList al = new ArrayList();
            printString(charArray, numArray, 0, al);
        }
        
        public static void printString(char[] charArray, int[] numArray, int depth, ArrayList al)
        {
            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++)
                {
                    if (!al.Contains(i))
                    {
                        numArray[depth] = i;
                        al.Add(i);
                        printString(charArray, numArray, depth + 1, al);
                        al.Remove(i);
                    }
                }
            }
        }
    }
}

Output
======
abcd
abdc
acbd
acdb
adbc
adcb
bacd
badc
bcad
bcda
bdac
bdca
cabd
cadb
cbad
cbda
cdab
cdba
dabc
dacb
dbac
dbca
dcab
dcba
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