Generating combinations using the Backtracking algorithm

advertisements

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!


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);
        }
    }
}