Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 716
marseilles84 Avatar asked Jun 21 '26 08:06

marseilles84


2 Answers

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);
like image 104
ispiro Avatar answered Jun 22 '26 23:06

ispiro


Permutations with repetition is essentially counting in another base.

public static void Permutations(int digits, int options)
{
    double maxNumberDouble = Math.Ceiling(Math.Pow(options, digits));
    int maxNumber = (int)maxNumberDouble;
    for (int i = 0; i < maxNumber; i++)
    {
        Console.WriteLine(Convert.ToString(i, options).PadLeft(3, '0'));
    }
}

The example that you've printed is essentially counting from 0 to 8 in base 2.

like image 40
Servy Avatar answered Jun 22 '26 21:06

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!