Search code examples
c#arraysdatagridlanguage-agnostic

How to return a grid of numbers from 1-D int array?


At the moment, I have a 1D array of ints that are used to form a 9x9 grid of numbers (but could be any size). I would like to input an index and return a 3x3 grid of numbers, effectively breaking the 9x9 grid up into 3x3 grids (Think Sudoku).

So far I have tried two nested loops, one that loops for the height of the grid, and inside that, one that loops for the width of the grid. But I'm having trouble making it work with anything other than the first 3x3 grid, or when the size changes from 9x9.

What I have so far:

int squareWidth = 3;
int squareHeight = 3;

int index = 0;
for (int i = 0; i < 3; i++)
{
    for (int j = index; j < 3; j++)
    {
     Console.WriteLine(array[j]);
    }
   index+=9;
}

4x4 Grid example should return a 2x2 grid but in a 1D array.

Imagine the first 2x2 grid is 1,2,2,4. The numbers found at index 0,1,4,5.

The second 2x2 grid is 7,2,4,5. The numbers found at index 2,3,6,7.

var gameboard = new int[] { 
1, 2, 7, 2,
2, 4, 4, 5,
4, 2, 1, 3,
3, 1, 2, 2 };

GetByGrid(2);

Should return

7,2,4,5

Since I input 2 into GetByGrid() it should return the 2x2 grid

GetByGrid(3);

Should return

4,2,3,1

Further clarification on how the grid is broken up. This is a 4x4 playing board with four 2x2 grids. A 9x9 playing board would have 9 3x3 grids.

1,2 | 7,2
2,4 | 4,5
---------
4,2 | 1,3
3,1 | 2,2

Solution

  • Thanks for the help

    Heres how I solved it

    Height, Width, the length of a row are all defined elsewhere

    public void GridToSquare(squareIndex)
    {
    int rowNum = squareIndex / (maxNum / width) * height;
    int colNum = squareIndex % (maxNum / width) * width;
    
           for (int row = rowNum; row < height + rowNum; row++)
           {
               for (int column = colNum; column < width + colNum; column++)
               {
                   Console.WriteLine(theArray[maxNum * row + column]);
               }
           } 
    }