简体   繁体   中英

C# fill 2D array matrix using single for loop

I'm currently messing around with 2D arrays. I want to Fill a 2D array with a count. I've managed to do this using 2 nested for loops. (That's probably the easiest way of doing it right?)

//create count
int count = 1;

for (int row = 0; row < matrix.GetLength(0); row++)
{
    for (int col = 0; col < matrix.GetLength(0); col++)
    {
        matrix[row, col] = count++;
    }
}

I was just curious, is it also possible to fill this 2D array using only a single for loop?

I thought of making a loop that counts the rows. When the rows reaches the end of the array the column wil be increased by 1. This could probably be done by using some if, if else and else statements right?

Does someone here have any idea how to make this work?

Here you go

int[,] matrix = new int[5, 10];     
int row = matrix.GetLength(0);
int col = matrix.GetLength(1);      

for (int i = 0; i < row * col; i++)
{
    matrix[i / col , i % col] = i + 1;
}

https://dotnetfiddle.net/Lv9DvT

Yes, of course you can.

for(int i = 0; i < matrix.GetLength(0) * matrix.GetLength(1); i++)
{
    int row = i / matrix.GetLength(1);
    int column = i % matrix.GetLength(1);

    matrix[row, column] = i;
}

Works with NxN arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM