Question

I have been working on generating 3 combinations of numbers using the Backtrack Algorithm and I have done thus far the following:

        static int a, b, c;

    static void Combo(int a,int b, int c)
    {
        if (a != 10)
        {
            Combo(a, b, c);
            a++;

        }

            if (b != 10)
            {
                 Combo(a, b, c);
                b++;

            }


        if(c != 10)
        {
                    Combo(a,b,c);
            c++;

        }
        Console.WriteLine("( {0}, {1}, {2})",a,b,c);


    }

And the Main Method:

        static void Main(string[] args)
    {
        Console.WriteLine("Press Any Key to Start Generating xxx number Combination");
        Console.ReadKey();

        Combo(0,0,0);
        Console.WriteLine("Combo function has finished Successfully!");
        Console.ReadKey();


    }

I get a message on cmd saying "Process is terminated due to StackOverFlowException . "

Is there a Problem with my code? If not, could you please help me how to get around this over Flow Problem Note: I want only a recursive backtracking algorithm; I am not looking for anything fancy, creative that is out of my League.

Thanks Forwards!

Was it helpful?

Solution 2

As suggested by others you're never reaching the line that allows you to increment the counter. Try this algorithm that gives you all "xxx" combinations (000 to 999) and also avoids the generation of duplicates (Sayse's solution generates duplicates):

static void Combo(int a, int b, int c)
{
    if (a < 10)
    {
        if (b < 10)
        {
            if (c < 10)
            {
                Console.WriteLine("( {0}, {1}, {2})", a, b, c);
                Combo(a, b, ++c);
            }
            else
            {
                c = 0;
                Combo(a, ++b, c);
            }
        }
        else
        {
            c = 0; b = 0;
            Combo(++a, b, c);
        }
    }
}

OTHER TIPS

Ignore my first comment, you increment a after you call combo, thus your stuck as thusly

static void Combo(int a,int b, int c)
    {
        if (a != 10)
        {
            Combo(a, b, c);
            a++;  <-- This is never reached

a remains at 0 for its lifetime try incrementing during your calls to combo such as

    static void Combo(int a,int b, int c)
    {
        if (a >= 10)
        {
            Combo(++a, b, c);

After further testing, I believe you are after the following (Nested if statements w/ increments):

    static void Combo(int a, int b, int c)
    {
        Console.WriteLine("( {0}, {1}, {2})", a, b, c);
        if (a < 10)
        {
            Combo(++a, b, c);
            if (b < 10)
            {
                Combo(a, ++b, c);
                if (c < 10)
                {
                    Combo(a, b, ++c);
                }
            }
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top