I'm working for finding all permutations of three numbers 1,2,3 using backtracking
I defined a,b,c as the following:
static int a=1;
static int b=2;
static int c=3;
static int aCount;
static int bCount;
static int cCount;
and the method perm, that finds each any every permutation of (1,2,3) is the following:
static void perm(int a, int b, int c)
{
Console.WriteLine("( {0}, {1}, {2} )", a, b, c); // (1,2,3 )
if (aCount<2)
{
aCount++;
// perm(a, b, c); no need for this one..It's already done above ^
perm(a,c,b); // (1,3,2 )
}
else if(bCount<2)
{
bCount++;
perm(b,a,c); //(2,1,3)
perm(b,c,a); //(2,3,1)
}
else if(cCount<2)
{
cCount++;
perm(c,b,a); //(3,2,1)
perm(c,a,b); //(3,1,2)
}
}
It works, but the result is not satisfying. (there must be a logical problem in the code).
there are lots of duplicates, for instance, and I can't get my code any better than this step.
Is there another way (like adding or subtracting a,b,c ) that can cure my code?
The Gig is there are only a recursive backtracking accepted in the code (hence the difficulty I am having).
Thank You Forwards guys for Your Help.
UPDATE:
I have updated the code, trying to fix what I can, and got it working, with less erroneous outupt:
static void perm(int a, int b, int c)
{
Console.WriteLine("( {0}, {1}, {2} )", a, b, c); // (1,2,3 )
if (aCount < 2)
{
aCount++;
// Console.WriteLine("( {0}, {1}, {2} )", a, b, c); // (1,2,3 )
// perm(a, b, c);
perm(a, c, b);
if (bCount < 2)
{
bCount++;
perm(b, a, c);
perm(b, c, a);
if (cCount < 2)
{
cCount++;
perm(c, b, a);
perm(c, a, b);
}
}
}
}
the Output on command seems to be better
how can I do it more efficiently, and better?