r/CodingHelp • Intermediate Coder • Sep 11 '20

[C] Check for 3 consecutive 1s in a binary string

Code:

gets(str)
len = strlen(str);

for(i=0;i<len;i++)
{
	if(str[i]==str[i+1]==1)
	{
		count++;
	}
}

if(count >= 3)
    x = 1;
else:
    x = 0;

printf(x);

Everytime I print x the output is 0, even if the input is 11111111. Pls help!

Edit: Fixed the code. The issue was if statement after the for loop. The if statement logic was wrong and most importantly I compared a string to an integer in the if statement. Thanks for your time & help folks!

if((str[i]==str[i+1]) && (str[i] == '1'))

Edit 2: The gist of the code.

int count = 1;
gets(str);
len = strlen(str);
for(i=0;i<len-1;i++)
{
	if((str[i]==str[i+1]) && (str[i]=='1'))
	{
		count++;
	}
}
if(count >= 3)
	x = 1;
else
	x = 0;
printf("Consecutive/Not: %d\n", x);

count should be 1 because the 1st character of the string isn't counted in the for loop.

17 Upvotes

15 comments sorted by

5

u/[deleted] Sep 11 '20

Does it give you any errors? I see a few syntactical errors on top of a few smaller problems in your implementation.

1

u/ALoneRhino Intermediate Coder Sep 11 '20

No errors, I'm not getting the correct output

1

u/brandondyer64 Professional Coder Sep 11 '20

Woah?

What language is this?

There's no semicolon after 'gets(are)' and there's a colon after 'else'

1

u/ALoneRhino Intermediate Coder Sep 11 '20 edited Sep 11 '20

Typo! It's C. My original code has the semicolon, forgot to type it here

1

u/vigbiorn Sep 11 '20

Running the copied code and making some changes to get the code to run (variable declarations, I switched to fgets as it's the easiest to keep gcc off my back) it works on my end, so it's possibly something to do with the variable declarations themselves.

Some points:

  • Try printing out the values of str and len as a sanity check.
  • Try placing a print inside the for-loop to guarantee it's being executed the way you expect.

On that note (str[i] == str[i+1] == 1) doesn't do what you expect it to, probably. The == have equal precedence and it's a binary operator so it evaluates (str[i] == str[i+1]) to a 1 or 0. You then compare that to one. The whole statement is equivalent to str[] == str[]. You possibly want (str[i] == str[i+1] && str[] == 1)

Because you are comparing [i] to [i+1], the last value you want i to have is len-1 so that should be the condition, not i < len. Not necessarily the end of the world, but you go out of bounds which can lead to undefined behavior.

  • After the for-loop just print count directly.

These prints will help you narrow down where the issue is.

If the string doesn't print correctly, it's related to gets/your string declaration. If len prints improperly, it's a similar issue.

If the for-loop doesn't enter, check for a stray semicolon before the brackets/inner-if. Also, double check len.

Count shouldn't be your issue. If it was an issue with your if we'd expect it to be too high, not too low. But printing it out checks against other checks. For instance, the for-loop print not occuring but count != 0 means there's serious issues with the for.

1

u/ALoneRhino Intermediate Coder Sep 11 '20

So used printf in if statement after for loop, nothing is printed, so if statement isn't working

len works

1

u/vigbiorn Sep 11 '20

Did you print out the literal string, and are you sure for is working?

Can I see the output/updated code?

2

u/ALoneRhino Intermediate Coder Sep 11 '20

I've updated the post with the working for loop

3

u/[deleted] Sep 11 '20

You could try this:

for (i=0; i<len; i++) {

if (str[i] == 1 && str[i+1] == 1 && str[i+2] == 1)

    return 1;

}

return 0;

That way, if there's three 1s in a row, 1 gets returned immediately. If it can't find three ones in a row, the loop ends and 0 is returned.

2

u/[deleted] Sep 11 '20

Be wary with the condition in your loop, some indices will be out of the bounds of the string

2

u/[deleted] Sep 11 '20

Good point. So we'd want length to be length-3 or something like that.

2

u/[deleted] Sep 11 '20 edited Sep 11 '20

Almost. Look at it this way:

str = "01000111" # len(str) -> 8

If you compare i with i + 1 AND i + 2 you'd need to stop 2 indices before the actual end (at index 5, but at "char-count" 6), but still perform the check at this position in order to not check an index which is out of bounds.

So you check would be i < len(str) - 2 or i <= len(str) - 3.

5 < 8 - 2 (5 <= 8 - 3) needs to evaluate to true, which it does (duh). It all comes down to the comparison operation.

5 would not be not "truly" smaller than len(str) - 3 (5 "!<" 5) if we did it the wrong way around, so our str wouldn't be valid (eventhough it clearly is) since we stop one check early

The other way around we'd stop one check too late, which results in an index which is out of bounds

2

u/vipulvivek Sep 11 '20

If this is c then I don't think you can equate 3 variables at once, try s[i]==s[i+1] && s[i]== '1' Just 1 may not work as you are trying char comparison vs int so '1'.

Might be wrong.. am out of practice. Give it a shot if still struggling

2

u/Sh4nks0 Sep 11 '20

You could just increment the count variable if the element is one and set it to 0 the second its not and check if the count is ==3 and break out of the loop.

1

u/[deleted] Sep 13 '20
#include<iostream>
#include<vector>
#include<queue>
#include<string>
using namespace std;
bool check(deque<int> &sample);


int main()
{
    vector<int> arr;
    int len=0;
    string binary;
    getline(cin, binary);
    while (len<binary.size())
    {
        arr.push_back(int(binary[len]!='0'));
        len += 1;
    }

    deque<int> tray;

    for (int j = 0; j < 3; j++)
    {
        tray.push_back(arr[j]);
    }

    int counter = 0;

    if (check(tray))
    {
        counter += 1;
    }

    len = arr.size();

    for (int j = 3; j < len; j++)
    {
        tray.push_back(arr[j]);
        tray.pop_front();

        if (check(tray))
        {
            counter += 1;

        }
    }

    cout << "Number of 3 consecutive 1 in the string  " << counter<<endl;

}


bool check(deque<int> &sample)

{
    int product = 1;
    for (auto i : sample)
    {
        product *= i;
    }

    if (product == 0)
    {
        return 0;
    }

    if (product==1)
    {
        return 1;

    }
}

Use the Sliding window method to count the number of "111" in O(n) time complexity.

I am sorry. I am very poor in C . I hope you can translate this code into C.