【问题标题】:How to find 4 consecutive "1" in an array如何在数组中找到4个连续的“1”
【发布时间】:2021-08-17 22:30:59
【问题描述】:

我有一个数组,它形成一个如下所示的矩阵(矩阵代表一块土地):

  1  1  8  4  1  1
  7  1  2  6  1  8
  7  1  2  4  1  4
  7  1  6  2  1  8
  0  0  3  3  6  6

我需要在该数组中找到所有为 1 的垂直连续数字,并告诉我该连续行中第一个 1 的坐标(坐标为 arr[4][1] 的数量)。我被卡住了,如果有人能告诉我要在代码中添加什么。

#include <stdio.h>
#include <stdlib.h>

int length = 5, width = 6;

int main() {
    int arr[5][6] = { { 1,  1,  8,  4,  1,  1 },
                      { 7,  1,  2,  6,  1,  8 },
                      { 7,  1,  2,  4 , 1,  4 },
                      { 7,  1,  6,  2,  1,  8 },
                      { 0,  0,  3,  3,  6,  6 },
                    };
    int count = 0;
    
    for (int i = 0; i < length ; i++) {
        for (int j = width; j > 0; j--) {
            if (arr[i][j] == 1) {
                count++;
                printf("suitable jumps: %d %d\n", i ,j);
            }
        }
    }
}

【问题讨论】:

  • 代码中示例输入的输出应该是什么?
  • 建议:看看你是否可以解决一维情况,一旦你确定你有这个工作,然后尝试将它推广到你想要的二维情况
  • 交换循环嵌套顺序——您需要逐列检查,而不是逐行检查。但尚不清楚arr[2][4] 如何解决您的问题。当你有匹配时,增加count,如果没有,将它设置为1,但无论如何都需要为每个内部循环初始化。
  • IMO 的答案是 [0][1] 和 [0][4]

标签: arrays c for-loop multidimensional-array count


【解决方案1】:

如果我理解任务

#define length 5 
#define width 6
#define NCONS 4
#define NEEDLE 1



int main(void)
{
    int arr[length][width] =  
    {{1,  1,  8,  4,  1,  1},
     {7,  1,  2,  6,  1,  8},
     {7,  1,  2,  4 , 1,  4},
     {7,  1,  6,  2,  1,  8},
     {0,  0,  3,  3,  6,  6},
    };
   int sum;
    
    for (int i = 0; i <= length - NCONS; i++) {
        for (int j = 0; j < width; j++)
        {
            sum = 0;
            for(int next = 0; next < NCONS; next++)  sum+= arr[i + next][j];

            if(sum == NEEDLE * NCONS)
            {
                printf("%d consecutive vertical %d found at: [%d][%d]\n",NCONS, NEEDLE,  i ,j);
            }
        }
    }
}

https://godbolt.org/z/KhEGo1rKj

【讨论】:

    猜你喜欢
    • 2014-05-17
    • 1970-01-01
    • 2016-05-18
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    相关资源
    最近更新 更多