2D array will not send C # messages

I have a simple task to convert a square 2D array: (I need to do this very simply, without containers, etc.)

static void Main(string[] args) { double[,] a = new double[5, 5]; Random random = new Random(); for(int i = 0; i < 5; i++) { for(int j = 0; j < 5; j++) { a[i, j] = random.NextDouble(); } } for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { Console.Write(a[i, j] + " "); } Console.WriteLine(); } for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { double temp = a[i, j]; a[i, j] = a[j, i]; a[j, i] = temp; } } Console.WriteLine("\n\n\n"); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { Console.Write(a[i, j] + " "); } Console.WriteLine(); } Console.ReadKey(); } } 

I was expecting the return array to be the output. However, I have the same array. Please help me find out what I did wrong? Console output. The double array will not transmit

+6
source share
3 answers

This is because you are executing for loops from 0 to 5 . So you do the transpose twice.

For example, for i=0 and j=1 you transfer a[0,1] with a[1,0] and when i=1 and j=0 values โ€‹โ€‹of a[1,0] and a[0,1] returned to the starting position.

You can do an internal for from 0 to i , so the positions are swapped only once.

 for (int i = 0; i < 5; i++) { for (int j = 0; j < i; j++) { double temp = a[i, j]; a[i, j] = a[j, i]; a[j, i] = temp; } } 
+6
source

The third cycle swaps both diagonal halves of the array, you only need to swap elements from one half:

 for (int i = 0; i < 5; i++) { for (int j = 0; j < i; j++) { double temp = a[i, j]; a[i, j] = a[j, i]; a[j, i] = temp; } } 
+1
source

In your swap, you need to change the inner loop limit to avoid the double replacement problem. Edit: for(j = 0; j < 5; j++) to for(j = 0; j < i; j++)

0
source

All Articles