Reputation:
So i have a globar array and a recursive function. For example, recursive function performs itself 16 times, and bestOrder=array2D
line should be reached only twice. Program actually reach it only twice, but bestOrder changes its value every time array2D is changed (array2D[position] = i;
) in this line. BestOrder should contain 2 0 3 1 order, but at the end of the function it contains 3 2 1 0 (last value of the array2D). How can i fix that?
private static int[] bestOrder;
private static void Permutate(int[] array2D, int position, Point[] checkpoints)
{
if (position == array2D.Length)
{
if (GetPathLen(checkpoints, array2D) < min)
{
min = GetPathLen(checkpoints, array2D);
bestOrder= array2D;
}
return;
}
for (int i = 0; i < array2D.Length; i++)
{
bool found = false;
for (int j = 0; j < position; j++)
if (array2D[j] == i)
{
found = true;
break;
}
if (found) continue;
array2D[position] = i;
Permutate(array2D, position + 1, checkpoints);
}
}
Upvotes: 0
Views: 236
Reputation: 19149
Arrays are reference type means they are actually not copied when they are assigned to variables or passed to methods. Instead their references are passed (The pointer that points to same location in memory). One way is Clone
and cast to actually copy the array.
bestOrder = (int[])array2D.Clone();
Another way is to create empty array. and fill it by elements of another array.
bestOrder = new int[array2D.Length];
for(int i = 0; i < bestOrder.Length; i++)
{
bestOrder[i] = array2D[i];
}
Upvotes: 1