二维数组中的行中的三个值C#

时间:2018-12-03 11:01:59

标签: c# arrays .net

我正在尝试让我的程序检查我的 2d数组是否具有彼此相邻的相同值3

我目前有这段代码,但是每当我到达count == 2时,它就会返回true(很抱歉,它在荷兰):

    bool ScoreRijAanwezig(RegularCandies[,] speelveld)
    {
        bool rij = false;
        int count = 0;
   `    for (int i = 0; i < speelveld.GetLength(0); i++)
        {
            {
                for (int j = 0; j < speelveld.GetLength(1) - 2; j++)
                {
                    if (speelveld[i, j] == speelveld[i, j + 1])
                    {
                        count++;
                        if (speelveld[i, j + 1] == speelveld[i, j + 2])
                            count++;
                        if (count >= 3)
                        {
                            rij = true;
                            count = 0; 
                        }
                    }
                }
            }
        }
        return rij;
    }  

我怎么知道,只要计数达到 3 或更大,它只会返回true

1 个答案:

答案 0 :(得分:1)

如果我没看错,您正在连续寻找至少 3个相等的值:

[1 2 3 4 5
 5 7 8 9 1
 3 6 6 6 7   <- three 6 in a row (what we are looking for)
 3 7 8 9 0
 3 5 3 5 3]  <- just three 3, don't count
 ^
 three 3 but in a column, don't count

让我们实现它

// static: we don't use "this" in the method 
static bool ScoreRijAanwezig(RegularCandies[,] speelveld) {
  // row is too short 
  if (speelveld.GetLength(1) <= 2)
    return false;

  // scan each column
  for (int i = 0; i < speelveld.GetLength(0); ++i) {
    // we have at least 1 value in a row - it's a leftmost value
    RegularCandies current = speelveld[i, 0];
    int count = 1;

    // we are scanning row:
    //  if we have the same value, let's increment check count
    //  if not, let's start from the value again
    for (int j = 1; j < speelveld.GetLength(1); ++j) {
      if (current == speelveld[i, j]) {
        // increment and check: do we have 3 in the row?
        if (++count >= 3) 
          return true;
      }
      else {
        // sequence is broken, let's start again with count = 1 
        current = speelveld[i, j];
        count = 1; 
      } 
    }
  }

  // entire array has been scanned, no three in the row found
  return false;
}