We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

# Magic Square C#

on
Medium Priority
4,933 Views
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
{
static void Main(string[] args)
{
int n=1;
Magic(n);
}

public static void Magic(int n)
{
int[] A = new int;
int[] B = new int;

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()
{

}
}
}
Comment
Watch Question

## View Solution Only

Commented:
No, this code gets in an infinite loop. Try something like this:

namespace ConsoleApplication
{
class Class1
{
static int[] A = new int;

static void Main(string[] args)
{
for (int i = 0; i < 9; i++)
{
Array.Clear(A, 0, 9);
A = i + 1;
Magic(1);
}
}

public static void Magic(int n)
{
for (int i = 0; i < 9; i++)
{
bool newNumber = true;
for (int j = 0; j < n; j++)
{
if (A[j] == i + 1)
{
newNumber = false;
break;
}
}
if (newNumber)
{
A[n] = i + 1;
if (n == 8)
Print();
else
Magic(n + 1);
}
}
}

private static void Print()
{
Console.WriteLine("{0}{1}{2}{3}{4}{5}{6}{7}{8}", A, A, A, A, A, A, A, A, A);
}
}
}

Not the solution you were looking for? Getting a personalized solution is easy.

Commented:
you could do what muzzy2003;
or just exchange this part:
public static void Magic(int n)
{
static      int[] A = new int;
static     int[] B = new int;

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.
##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile