jmkotman
asked on
Magic Square C#
I am writing a Magic Square program that finds all the possible combinations of 1 to 9. I wrote the recursive part of it but it seems to just be going on forever. I want to print out all the possible ways of 1 to 9 without any repetitions. Is this right?
using System;
namespace ConsoleApplication4
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
int n=1;
Magic(n);
}
public static void Magic(int n)
{
int[] A = new int[10];
int[] B = new int[10];
for(int i = 1; i <= 9; i++)
{
if(B[i] == 0) // if i is free
{
B[i]=1;
A[n]=i;
if(n<9)
{
Magic(n+1);//recurse
}
else
{
TestMagic();//at the end
}
B[i]=0;
}
Console.Write(A[n]);
}
}
public static void TestMagic()
{
}
}
}
using System;
namespace ConsoleApplication4
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
int n=1;
Magic(n);
}
public static void Magic(int n)
{
int[] A = new int[10];
int[] B = new int[10];
for(int i = 1; i <= 9; i++)
{
if(B[i] == 0) // if i is free
{
B[i]=1;
A[n]=i;
if(n<9)
{
Magic(n+1);//recurse
}
else
{
TestMagic();//at the end
}
B[i]=0;
}
Console.Write(A[n]);
}
}
public static void TestMagic()
{
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
or just exchange this part:
public static void Magic(int n)
{
static int[] A = new int[10];
static int[] B = new int[10];
for(int i = n; i <= 9; i++)
{
The problem is that the static makes the number remember they were already used, and the i=n makes the n has a better validity, it will
stop as soon as n=9, and will not go depper and depper, even if n is bigger then 9.
I didnt understand why you set again B[i]=0; it will then go forever.