Hello. I am writing a program that uses a List<T> object to retain a list of int[] objects.
private int[] numbers = new int[9];
private List<int[]> theList = new List<int[]>();
It's basicaly a backtracking algorithm that constructs the numbers object, which contains a permutatio of the numbers 1..9, and after every complete construction adds the solution to the list:
list.Add(numbers);
I checked the construction and it works fine, but if I want to read/print/use the list after all the solutions are added, it only contains the number 9, in every entry of the integer vector.
My question is: why isn't the List object saving the exact state added to each of it's elements? Here is my code (I know it's messy, but it's experimental):
private int[] numbers = new int[9];
private List<int[]> theList = new List<int[]>();
public Executor()
{
}
private void BackTrack(int p)
{
int i;
for (i = 1; i <= 9; i++)
{
numbers[p] = i;
if (CheckCorrectness(p))
{
if (p == 8) AddSolution();
else BackTrack(p + 1);
}
}
}
private bool CheckCorrectness(int p)
{
int i;
for (i = 0; i < p; i++)
if (numbers[i] == numbers[p]) return false;
return true;
}
private void AddSolution()
{
theList.Add(numbers);
//uncomment line to that it generates the right solution
//for (int i = 0; i < 9; i++) Console.Out.Write(numbers[i] + " ");
}
public void Print()
{
for (int i = 0; i < list.Count; i++)
{
for (int j = 0; j < 9; j++)
{
Console.Out.Write(theList[i][j].ToString() + " ");
}
Console.Out.WriteLine();
}
Console.Out.WriteLine();
}
It should print:
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 9 8
1 2 3 4 5 6 8 7 9
and so on, but it prints:
9 9 9 9 9 9 9 9 9
9 9 9 9 9 9 9 9 9
9 9 9 9 9 9 9 9 9
It starts execution with BackTrack(0) and the it calls the Print() method.