0

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);
            }
        }
2
  • Read about reference/value types and You will understand :) Commented Nov 1, 2015 at 10:48
  • i did but it didnt quite help me in this situation Commented Nov 1, 2015 at 10:52

1 Answer 1

1

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];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.