简体   繁体   中英

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 .

Do not count total numbers of 1 in each line. 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.

SOLUTION thanks to 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

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. You need to reset c even if the new sequence isn't the longest.

Change the else if into

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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