简体   繁体   English

C#使用单个for循环填充2D数组矩阵

[英]C# fill 2D array matrix using single for loop

I'm currently messing around with 2D arrays. 我目前正在使用2D阵列。 I want to Fill a 2D array with a count. 我想用计数填充2D数组。 I've managed to do this using 2 nested for loops. 我已经设法使用2个嵌套的for循环来做到这一点。 (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? 我只是很好奇,是否也可以仅使用一个for循环来填充2D数组?

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? 当行到达数组的末尾时,列将增加1。这可以通过使用if,if else和else语句来完成吗?

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 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. 与NxN数组一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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