Search code examples
c#recursionpermutation

permutations with repeats algorithm with recursion


I'm having some trouble getting this to work using one function, instead of having to use many.

If I want to get permutations with repeats like 2^3. permutations with repeats

to get:

000
001
101
011
100
101
110
111

I can have this function:

   static void Main(string[] args)
    {
        three_permutations(2);
        Console.ReadLine();
    }


    static void three_permutations(int y)
    {

        for (int aa = 0; aa < y; aa++)
        {
            for (int bb = 0; bb < y; bb++)
            {
                for (int cc = 0; cc < y; cc++)
                {
                    Console.Write((aa));
                    Console.Write((bb));
                    Console.Write((cc));
                    Console.WriteLine();
                }
            }
        }

    }

But then to do 4 (like 2^4), the only way I can think is this:

  static void four_permutations(int y)
    {
            for (int aa = 0; aa < y; aa++)
            {
                for (int bb = 0; bb < y; bb++)
                {
                    for (int cc = 0; cc < y; cc++)
                    {
                        for (int dd = 0; dd < y; dd++)
                        {
                            Console.Write((aa));
                            Console.Write((bb));
                            Console.Write((cc));
                            Console.Write((dd));
                            Console.WriteLine();
                        }
                    }
                }
            }
     }

but I'm sure there's a better way using recursion I'm just not sure how to do it. I appreciate any help. Thanks.


Solution

  • void permutations(string text, int numberOfDigits, int numberOfChars)
    {
        if (numberOfDigits > 0)
            for (int j = 0; j < numberOfChars; j++)
                permutations(text + j.ToString(), numberOfDigits - 1, numberOfChars);
        else textBox1.Text += text + "\r\n";
    }
    

    and call:

    permutations("", 3, 2);