How to convert a 1D coordinate into 2D indexes in C#

1 Answer

0 votes
using System;
  
class Program
{
    static void Main() {
        int[,] array2d = { { 1,   2,   3,   6,  0},
                           {-5,  -4,   0,   7,  9},
                           { 1,  18, 100,  14,  6},
                           { 9,  10,  27,  12, 13} };
 
 
        int[] array1d = { 1, 2, 3, 6, 0, -5, -4, 0, 7, 9, 1, 18, 100, 14, 6, 9, 10, 27, 12, 13 };
         
        int cols = array2d.GetUpperBound(1) + 1;
         
        int index = 17;
         
        // int i = 3, j = 2;
         
        int i = index / cols;
        int j = index - (i * cols); // index % cols
 
        Console.WriteLine("i = " + i + " j = " + j);
         
         
        Console.WriteLine(array1d[index]);
        Console.WriteLine(array2d[i, j]);
    }
}
  
  
  
/*
run:
  
i = 3 j = 2
27
27
 
*/

 



answered Sep 18, 2023 by avibootz
edited Sep 18, 2023 by avibootz

Related questions

1 answer 164 views
1 answer 133 views
1 answer 154 views
1 answer 165 views
1 answer 178 views
1 answer 134 views
1 answer 149 views
...