简体   繁体   English

C程序-在数组中查找最大序列

[英]C program - find largest sequence in array

Given this example : 给出这个例子:

int arr[3][7] = {       {1,0,0,1,1,1,1},  //should output 4
                        {0,1,1,1,1,0,1},  //should output 4
                        {0,0,1,1,1,1,1}}; //should output 5

Find the largest sequence containing number 1 , and print line index and number of 1 . 查找包含数字1的最大序列,并打印行索引和数字1

Do not count total numbers of 1 in each line. 不要 在每行中 计算总数 1 Only if they are one after another . 只有他们一个接一个

here is my approach : 这是我的方法:

int main(){
    int i,j,c=0,count=0;

    int arr[3][7] = {   {1,0,0,1,1,1,1},  //output 4
                        {0,1,1,1,1,0,1},  //output 4
                        {0,0,1,1,1,1,1}}; // output 5

    for(i=0; i<3; i++){
        for(j=0; j<7; j++){
            if(arr[i][j] == 1){
                c++;
            } else if( arr[i][j] == 0 && c > count ) {
                count = c;
                c = 0;
            }
        }
        printf("%d\n", count);
    }

  return 0;
}

What i want to get as output now is 4,4,5 but i am getting 1,4,5. 我现在想要得到的输出是4,4,5,但是我正在得到1,4,5。

SOLUTION thanks to https://stackoverflow.com/users/1228887/twain249 解决方案感谢https://stackoverflow.com/users/1228887/twain249

int main(){
    int i,j,c=0,count=0;

    int arr[3][7] = {   {1,1,0,1,1,1,1},  //output 4
                        {0,1,1,1,1,0,1},  //output 4
                        {0,0,1,1,1,1,1}}; // output 5

    for(i=0; i<3; i++){
        for(j=0; j<7; j++){
            if(arr[i][j] == 1){
                c++;
            } else {
                count = c;
                c = 0;
            }
        }
        if(c > count){
            count = c;
        }
        printf("%d\n", count);
        c=0;
    }
    return 0;
}

You forgot to handle the case where the longest sequence is the end of the list 您忘记处理最长序列在列表结尾的情况

after the inner j loop add the following 在内部j循环之后,添加以下内容

if (c > count) {
    count = c;
}

Also you forgot to add a clear after each check. 您也忘记在每次检查后添加透明纸。

After the printout add 打印输出后添加

c = clear = 0;

EDIT: 1 more error. 编辑:另外1个错误。 You need to reset c even if the new sequence isn't the longest. 即使新序列不是最长的,也需要重置c

Change the else if into 如果更改为else

else if (arr[i][j] == 0) { // If isn't necessary if 0/1 are your only options
{
    if (c > count) {
        count = c;
    }
    c = 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM