Home > other >  How can I give the array in my function an general array for all the code?
How can I give the array in my function an general array for all the code?

Time:04-30

I am writing some code in C#. I have an array with values in it. As you can see in my code I have in my int[,] figuurI at row 1, column 1 number 1. In row 2, column 1 I have a 1 again. The number 1 will fill a box. The number 0 leaves the box empty. In this way I can create figures.

I have an function which make the figures rotate 90 degrees to the right. I should add that this happens when an arrow key is clicked.

Is it true that the values in the function are in an array? I want to store the values from the output of the function in an array. In that way I can run the function again if the user clicked again on the arrow key. Now it will rotate again 90 degrees to the right. Compared to the first array, the figure have now rotated 180 degrees and compared to the second array 90 degrees. How can I make this work?

using System;
class GFG {
     
    static void rotateRight(int[,] arr, int N)
    {

        for (int j = 0; j < N; j  )
        {
            for (int i = N - 1; i >= 0; i--)
            {
                Console.Write(arr[i, j]   " ");
            
            }
            Console.WriteLine();
        }
        Console.WriteLine("\n");
      }
     
  static void Main() {
                  
    int[,] figuurI = {{1, 0, 0, 0},
                      {1, 0, 0, 0},
                      {1, 0, 0, 0},
                      {1, 0, 0, 0} };
    rotateRight(figuurI, 4);

  }
}

CodePudding user response:

I suppose you want something like this - make a new array and copy the rotation into it:

class Gfg {
     
    static int[,] RotateRight(int[,] arr)
    {
        int n = arr.GetLength(0);
        int[,] r = new int[n,n];

        for (int j = 0; j < n; j  )
            for (int i = n - 1; i >= 0; i--)
                r[j, n-i-1] = arr[i, j];
        
        return r;
    }
     
  static void Main() {
                  
    int[,] figuurI = {{1, 0, 0, 0},
                      {1, 0, 0, 0},
                      {1, 0, 0, 0},
                      {1, 0, 0, 0} };
      
    var figuur2 = RotateRight(figuurI);
      
  }
}

figuur2 is now:

{
  {1, 1, 1, 1},
  {0, 0, 0, 0},
  {0, 0, 0, 0},
  {0, 0, 0, 0} 
}
  • Related