【问题标题】:Counting occurrences of integers in a two-dimensional array in C# visual studio在 C# Visual Studio 中计算二维数组中整数的出现次数
【发布时间】:2020-09-23 22:20:57
【问题描述】:

我的代码循环遍历二维数组并计算每个整数 1-9 的出现次数,并将它们输出到各自的标签中。

这是我自己写的,并且有点努力去做。

有人可以向我解释为什么会这样吗?特别是这一行:

count[numbers[row, col]]++;

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();

【问题讨论】:

  • 这有助于阐明吗? int theNumberAtRowCol = numbers[row, col]; count[theNumberAtRowCol] += 1;
  • 仅供参考,您也可以这样做foreach(var x in numbers) count[x]++;
  • @JohnnyMopp, count[theNumberAtRowCol] += 1; 对我来说很有意义。另一条线对我来说不是很清楚。我一直在与数组作斗争。我知道它只是循环遍历数组中的每个数字并根据遇到的数字递增计数器。我似乎无法想象它足以有信心记住如何去做。
  • @juharr 这看起来要简单得多。这个 foreach 会取代嵌套的 for 循环吗?
  • @Kayair 是的,多维数组在 foreach 中使用时将遍历所有值。所以如果你有一个 3D 甚至 4D 阵列,这将起作用。请注意,int[][]int[,] 之间的锯齿状阵列不是这样工作的。

标签: c# arrays visual-studio counting


【解决方案1】:
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 板。

【讨论】:

    猜你喜欢
    • 2021-09-02
    • 2023-04-02
    • 2022-01-07
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    相关资源
    最近更新 更多