【问题标题】:Three values in a row in a 2d array c#二维数组中连续三个值c#
【发布时间】:2018-12-03 11:01:59
【问题描述】:

我正在尝试让我的程序检查我的 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

【问题讨论】:

    标签: c# arrays .net


    【解决方案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;
    } 
    

    【讨论】:

    • 感谢您的评论和帮助,但有一个小问题RegularCandies current = speelveld[i, 0]; 会返回它当前所在的参数还是有什么不同?
    • current 是我们检查的候选值(如果它重复 3 次)。我们假设最左边的值 - speelveld[i, 0] 连续重复 3 次:4 4 4 ... 如果我们失败,例如4 4 2 ... 我们开始测试 2 如果我们有:4 4 2 2 2 ... 然后,比如说,在下一次失败时 4 4 2 1 ... 我们继续使用 1 等等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2011-08-23
    • 2013-02-05
    • 2016-04-01
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    相关资源
    最近更新 更多