c# - 在 C# Visual Studio 中计算二维数组中整数的出现次数
问题描述
我的代码循环遍历二维数组并计算每个整数 1-9 的出现次数,并将它们输出到各自的标签中。
我自己写了这个,有点努力去做。
有人可以向我解释为什么会这样吗?特别是这一行:
计数[数字[行,列]]++;
int[ , ] numbers = { { 1, 8 },
{ 4, 5 },
{ 7, 9 },
{ 3, 1 },
{ 9, 3 },
{ 5, 9 },
{ 8, 8 },
{ 9, 9 },
{ 7, 3 },
{ 2, 1 },
{ 5, 4 } };
int[] count = new int [10]; // use this for counting occurrences
// nested loop --- need to loop through the rows, and then the columns
// update the count array with the corresponding values, then increment
for (int row = 0; row < numbers.GetLength(0); row++)
{
for (int col = 0; col < numbers.GetLength(1); col++)
{
count[numbers[row, col]]++;
}
}
oneLabel.Text = count[1].ToString();
twoLabel.Text = count[2].ToString();
threeLabel.Text = count[3].ToString();
fourLabel.Text = count[4].ToString();
fiveLabel.Text = count[5].ToString();
sixLabel.Text = count[6].ToString();
sevenLabel.Text = count[7].ToString();
eightLabel.Text = count[8].ToString();
nineLabel.Text = count[9].ToString();
解决方案
count[numbers[row, col]]++;
首先,您需要知道 numbers[row, col] 仅访问一个数字,并且正在获取该数字并在 count 数组中使用它;
[0,0][1,0][2,0]
[0,1][1,1][2,1]
[0,2][1,2][2,2]
每个方括号仅代表一个数字。您正在获取该数字并将其放入计数数组中,就像 count [0,0] 但 [0,0] 只是一个像 1 或其他东西的 int。
希望这会有所帮助,我喜欢把它想象成一个 tiktactoe 板。
推荐阅读
- python - 如何使用标准python检测单变量数据的“相邻值之间”的异常值
- postgresql - 我需要计算每笔交易的字段或更新吗?
- sql - 在我的查询中当 RowNum =1 没有得到空值
- intellij-idea - 如何让 Intellij 自动显示提示和建议?
- c++ - 为什么 GCC 在 Clang 不使用它的地方插入 mfence?
- java - 如何在Java中将两个字节相加,如果有溢出则回绕
- compiler-construction - 如何为词法和句法错误恢复编写语法?
- java - Logstash/Gelf 未存储所有 MDC
- swift - Swift 可编码和模型数组
- linux - 为什么像 cat 这样的命令在后台运行时会立即退出?