'i'm having some problem with saveing the vaule of the longest fence

enter image description here

I'm having some problem with saveing the vaule of the longest fence.

I tried this:

int longestFence(char input [], int size)
{
    int i , max = 0, count = 0;

    for(i = 0; i < size ; i++)
    {
        if(input[i] == '|'  && input[i] == '-')
        {
            count = 1;
        }
        if(input[i] != input[i + 1])
        {
            count++ - 1;
        }
    }
    return count;
}
c


Solution 1:[1]

In practice, to detect is the fence is still valid, you just have to check if the current symbol is different or not than the previous one.

You also have to check if the current count is longer or not than the previous longest one.

Besides, I modified the random string generator: the current one is rather inefficient.

In addition, the string generated is not terminated by the Null character. I also modified it.

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

#define MAX 10

int longestFence (char input[], int size) {
    if (size == 0) return 0;
    int max_count = 0;
    int count = 1;
    for (int i = 1; i < size; ++i) {
        if (input[i] != input[i-1]) {
            count++;
        } else {
            if (count > max_count) max_count = count;
            count = 1;
        }
    }
    if (count > max_count) max_count = count;
    return max_count;
}

int main() {
    char string[MAX+1];
    char symbols[] = {'|', '-'};
    srand (time(NULL));
    int length = rand() % (MAX+1);
    for (int i = 0; i < length; ++i) {
        int val = (rand() / 16) % 2;
        string[i] = symbols[val];
    }
    string[length] = '\0';
    printf ("String is: %s\n", string);
    printf ("Longest fence = %d\n", longestFence (string, length));
    return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1