我有一个boolean [30,10]的二维数组。这些都设置为false。我只想检查行是否已填充。这样的例子。如果第0列的行全部为true。然后我调试返回说:“第一行都正确”。其他所有列也是如此。如果第5列及其行也全部为true。然后我说:“布尔的第五行都正确”
private bool[,] grid = new bool[30,10];
for( int y = 0; x < grid.GetLength(0); y++ )
{
for( int x = 0; x < grid.GetLength(1); x++ )
{
if ( grid[y,x] == true )
{
Debug.Log(y + "th rows are filled!");
}
}
}
只有我的伪代码。他们不工作,我知道。但是有人知道怎么做吗?
答案 0 :(得分:1)
要循环检查值数组是否全部正确,请执行以下操作:
private bool[,] grid = new bool[30,10];
for(int y = 0; x < grid.GetLength(0); y++){
bool row = true;
for(int x = 0; x < grid.GetLength(1); x++)
row &&= grid[y,x]; // row stays true until it encounters a false
if (row) Debug.Log(y + " row is filled");
}
答案 1 :(得分:1)
尝试一下:
int rows = 30;
int cols = 10;
bool[,] grid = new bool[rows,cols];
InitializeGrid(grid);
for (int row = 0 ; row < rows ; ++row )
{
bool isAllTrue = true;
for( int col = 0 ; col < cols ; ++col {
if ( !grid[row,col] )
{
isAllTrue = false;
break;
}
}
if (isAllTrue)
{
Console.WriteLine($"Row {row} is all true");
}
}
答案 2 :(得分:1)
首先,这是一个非常小的问题,在您的第一个for循环中,您编写了
for (int y = 0; **x** < grid.GetLength(0); y++)
您应该写:
for (int y = 0; **y** < grid.GetLength(0); y++) ;
但不幸的是,这不是问题:(
在您的代码中,您将遍历一行中的每个元素并检查其是否为真,这就是问题所在,该if语句:
if(grid[y,x] == true){
Debug.Log(y + "th rows are filled!");
正在检查第一个元素是否为true,如果是,它将打印出整体 行中填充了真实变量。相反,我提供了以下解决方案:
bool[,] grid = new bool[2,2];
bool isRowTrue = true;
for (int y = 0; y < grid.GetLength(0); y++)
{
for (int x = 0; x < grid.GetLength(1); x++)
{
if (grid[y, x] == false)
{
isRowTrue = false;
break;
}
}
if (isRowTrue == true)
{
Debug.Log(y + "th are all true!");
}
else {
isRowTrue = true;
}
}
我希望我已经正确理解了您的问题,如果不能的话,我道歉,请告诉我,我将尽力理解和帮助。
答案 3 :(得分:1)
您可以像这样在单个foreach循环中完成
private bool[,] grid = new bool[30,10];
bool allAreTrue = true;
foreach(var b in grid)
{
if(!b)
{
allAreTrue = false;
// No need to check others anymore
break;
}
}
或者您可以在使用Linq All将多维数组转换为可枚举后使用Linq OfType
using System.Linq;
...
private bool[,] grid = new bool[30,10];
var allAreTrue = grid.OfType<bool>().All(b => !b);