C++ How to find out most consecutive digits in an array? - c++

Hi guys I'm trying to write a code where when i type a binary string I need to mind the most consecutive numbers of occurrence 1 has occurred. For example, if i type 00111001, it should be 3, 1100111011111, it should be 5 etc. This is my code so far.
int main () {
string s1;
cin >> s1;
int l1=s1.size()-1; // length-1 hence the for loop array doesnt go out of bounds
int max=0; // this tells us the max number of occurrence
int count=0;
for (int i=0;i<l1;i++) {
if (s1[i]=='1' && s1[i+1]=='1') { // if s[0] and s[1] are both 1, it adds 1
count++;}
if (count>0 && count>max)
{max=count; // storing the count value in max.
}
if (s1[i]=='0' || s1[i+1]=='0'){ //resetting count if it encounters 0
count=0;
}
}
max=max+1;
cout << max << '\n' << endl;
The issue is if I write 1111001 it runs (I get 4), but when i type 1100111001 I get 2. Don't get why there's ambiguity. Please let me know what I need to do
Thanks

I'd only increment the count in case of 1, and zero it when 0 is reached.
whenever count is bigger than max, assign count to max and that's it.
btw, I get 3 for the input 1100111001 with your program.
#include <iostream>
using namespace std;
int main() {
string s1;
cin >> s1;
int l1 = s1.size();
int max = 0;
int count = 0;
for (int i = 0; i < l1; i++)
{
if (s1[i] == '1')
{
count++;
}
else
{
count = 0;
}
if (count > max)
{
max = count;
}
}
cout << max << '\n' << endl;
}

Let's solve this using find, given string s1 which contains your input string you can just do:
auto max = 0;
for(auto start = find(cbegin(s1), cend(s1), '1'); start != cend(s1); start = find(start, cend(s1), '1')) {
const auto finish = find(start, cend(s1), '0');
const auto count = distance(start, finish);
if(count > max) {
max = count;
}
start = finish;
}
Live Example

I want to offer you such an option for calculating through tokens and sorting:
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string s1;
cin>>s1;
istringstream s(s1);
vector<string> result;
while (std::getline(s,s1,'0')) {
result.push_back(s1);
}
sort(result.begin(),result.end(),[](const string &a, const string &b){ return a.length()>b.length();});
cout << result.at(0).length() << endl;
return 0;
}

Related

Find and output longest string word c++

I'm pretty new to programming and recently started working with strings. In my mind, this idea should somewhat work, but I have no idea what's wrong.
So I go through the string, with simb++ (to find length of the word) and where++ (to find where in the string am I) until I find a space, where I compare with the longest word I've found so so far (temp) and if it's longer, I make it the longest and find starting point of the word (start). When the for(...) ends, I write the word in the last for()
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
string longest="";
int simb=0;
int temp=0;
int where=0;
int start=0;
cout<<"Input sentence"<<endl;
getline(cin,sentence);
for(int i=0 ; i<sentence.size() ; i++)
{
if(sentence[i]!=' ')
{
simb++;
where++;
}
if(sentence[i]==' ')
{
if(simb>temp)
{
where++;
simb++;
start=where-simb;
temp=simb;
}
simb=0;
}
}
for(int m=start ; m<=temp ; m++)
{
longest=longest+sentence[m];
}
cout<<"longest sentence"<<longest<<endl;
return 0;
}
There are a number of issues in your code:
if simb<=temp you don't increment where, you can just remove where completely and use i instead.
incrementing simb before calculating start results in start being 1 less than it should be
you don't check the length of last word in the string (assuming the string doesn't end with whitespace)
your final for loop goes from start to temp but should go from start to start + temp
Fixing these issues gives:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
int simb = 0;
int temp = 0;
int start = 0;
string sentence = "test test2 test 3 test 4 foo longest";
for (int i = 0; i <= sentence.size(); i++)
{
if (i != sentence.size() && sentence[i] != ' ')
{
simb++;
}
else
{
if (simb > temp)
{
start = i - simb;
temp = simb;
}
simb = 0;
}
}
string longest = "";
for (int m = start; m < start + temp; m++)
{
longest = longest + sentence[m];
}
cout << "longest sentence: '" << longest << "'\n";
return 0;
}
Note that using std::istringstream would be much simpler:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string sentence = "test test2 test 3 test 4 foo longest";
std::string longest;
std::stringstream ss(sentence);
std::string word;
while (ss >> word)
{
if (word.length() > longest.length())
{
longest = word;
}
}
std::cout << "longest sentence: '" << longest << "'\n";
return 0;
}
You can try this:
1.first locate where the spaces are.
2.calculate the gap between the two consequent words/strings.
3.find the word which has the maximum gap.
4.the world which has the maximum gap will be the longest one.
It's not c++ specific you can try this with any language.
Here is the c++ example:
#include <iostream>
#include <string>
using namespace std;
int main(){
//to get the user input
cout<<"Enter a sentence:"<<endl;
string s;
getline(cin,s);
// here the old value refers to the last index having space
// gap is the difference betweeen latest index having space and the old value
// max stores the maximum gap
int old=0;
int max=0;
int gap=0;
//these two values store the starting and ending index of longest string
int startIndex;
int endIndex;
// This for loop determines the maximum gap and calculates the starting
// and ending index of the longest word.
for(int i=0;i<s.size();i++){
if(isspace(s[i])|| i==s.size()){
if((i-old)>gap){
max=(i-old);
startIndex=i-max;
endIndex=i;}
gap=(i-old);
old=i+1;}
}
cout<<"longest string in the sentence is:";
//here we are using the determined starting and ending indices to print the longest word
for(int i=startIndex;i<=endIndex;i++){
cout<<s[i];
}
return 0;
}

why does it give me bigger than 4 always?

I am trying to get the numbers bigger than 4 after I loop in every other number, but the problem is that it keeps giving me bigger than 4 even tho the number isn't bigger than 4. thank you!
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool isvalidcc(const string& s)
{
vector<char> v (s.begin(), s.end());
for(auto i=0 ; i<v.size();i+=2)
{
if (v.at(i)>'4')
{
cout<<v.at(i)<<"bigger than 4"<<endl;
}
else
{
cout<<v.at(i)<<"smaller than 4"<<endl;
}
}
return false;
}
int main()
{
vector<string> cardnumbers = {
"371449635398431"
};
int i;
vector<string>::iterator itr;
for (i = 1, itr = cardnumbers.begin(); itr != cardnumbers.end(); ++itr, i++) {
// cout << i << " "
// << *itr
((isvalidcc(*itr)));
}
return 0;
}
I figured it out
Because v.at(i) is a char instead of an int it converts it into ascii code.
this means u have to convert the char in to an int the right way.
if (v.at(i) - '0' >4)
the - '0' will convert it to an int the right way otherwise it will return the wrong values, u can check this by making a new int variable and cout <<
int n = v.at(i);
cout << n;

Displaying all prefixes of a word in C++

I am trying to do is display all the suffixes of a word as such:
word: house
print:
h
ho
hou
hous
house
What I did is:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char cuvant[100];
int i,k;
cin>>cuvant;
for(i=0;i<strlen(cuvant);i++)
{
for(k=0;k<i;k++)
{
if(k==0)
{
cout<<cuvant[k]<<endl;
}else
{
for(k=1;k<=i;k++){
if(k==i) cout<<endl;
cout<<cuvant[k];
}
}
}
}
}
What am I doing wrong?
You're over-complicating it. Here's a simpler way:
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string s;
std::cin >> s;
for (std::string::size_type i = 0, size = s.size(); i != size; ++i)
std::cout << std::string_view{s.c_str(), i + 1} << '\n';
}
If you don't have access to a C++17 compiler, you can use this one:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
int main() {
std::string s;
std::cin >> s;
for (auto const& ch : s) {
std::copy(s.c_str(), (&ch + 1),
std::ostream_iterator<decltype(ch)>(std::cout));
std::cout << '\n';
}
}
Even so, I think it would be better for your learning progress to use a debugger to finger out the problem yourself. Here the problems with your code:
For the i=0 (the first iteration of your outer loop) the for(k=0;k<i;k++) will not be executed at all, as k<0 evaluates to false.
And having a running variable (k) that you change in two for loops that are nested, is most of the time also an indication that something is wrong.
So what you want to do: You want to create each possible prefix, so you want to create n strings with the length of 1 to n. So your first idea with the outer loop is correct. But you overcomplicate the inner part.
For the inner part, you want to print all chars from the index 0 up to i.
int main() {
char cuvant[100];
std::cin >> cuvant;
// loop over the length of the string
for (int i = 0, size = strlen(cuvant); i < size; i++) {
// print all chars from 0 upto to i (k<=0)
for (int k = 0; k <= i; k++) {
std::cout << cuvant[k];
}
// print a new line after that
std::cout << std::endl;
}
}
But instead of reinventing the wheel I would use the functions the std provides:
int main() {
std::string s;
std::cin >> s;
for (std::size_t i = 0, size = s.size(); i < size; i++) {
std::cout << s.substr(0, i + 1) << std::endl;
}
}
For this very simple string suffix task you can just use:
void main()
{
std::string s = "house";
std::string s2;
for(char c : s)
{
s2 += c;
cout << s2 << endl;
}
}
For more complicated problems you may be interested to read about Suffix Tree
Your code is wrong, the following code can fulfill your requirements
#include <iostream>
using namespace std;
int main()
{
char cuvant[100];
int i,k;
cin>>cuvant;
for(i=0;i<strlen(cuvant);i++)
{
for (k = 0; k <= i; ++k)
{
cout<<cuvant[k];
}
cout<<endl;
}
}

Store and print characters but the output is not what is expected

I'm very new to C++. This code is supposed to store and print out every other number and stop when given the symbol #, but the output is weird. It outputs something like 0x6fdd90. Any help would be much appreciated.
#include <iostream>
#include <string>
using namespace std;
int main(){
string s[11];
int count = 1, wordlength = 0;
char a;
cin.get(a);
while (a != '#'){
if (wordlength == 10)
break;
if (count % 2 != 0){
s[wordlength] = a;
wordlength++;
}
cin.get(a);
count++;
}
s[wordlength] = '\0';
cout << s;
return 0;
}
cout << s;
Is printing the address of the 1st element in your array s.
You may want to loop through s to print all the elements.
for (int i =0; i < sizeof(s)/sizeof(s[0]); i++) {
cout<< s[i] << "\n";
}
It is better to user char array than string array for your purpose.

How to make a while loop till there is something to be readen c++

I know that you probably gona again vote me down, I really don't understand this but im really stuck at something and cant figure it out , there is no such information anywhere in the web , neither in my book for the course, so I have this assignment where I need make 2 sums of containers where the difference between 2 sums is the lowest , so the program is done is working perfectly calculated everything however , in my assignment:
The user enter on one row unkwonw length numbers so after that I do all kind of sums between them and find the one with lowest difference between.
Ok but the way I wrote the code I use one while(true) so that to work with infinity testcases(as from assignment) and in this while(true) I have another while(cin>>(SOMEINT)) loop and push it back in a vector , and after it reads new line it just break the wile and continue with the calculation.
However in our test software this one give runtime error since after finding some cases then it start print infinity 0 0 since there is nothing to enter but the while(true) just continues.
I mean I just want to make it that way that the while is till user enters something , for instance you enter 30 50 90 it will return 80 90 , then wiat for another entry and so on.
CODE:
#include <iostream>
#include <string>
#include<vector>
#include <sstream>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <climits>
using namespace std;
const int length = 17000;
int power(int x){
int sum =2;
for(int i = 0;i<x;i++) {
sum *= 2;
}
return sum;
}
bool ison(int i,int x)
{
if((i>>x) & 1)return true;
return false;
}
int main()
{
while(true){
vector<int> Vec;
int cur = 0;
while (cin >> cur) {
Vec.push_back(cur);
if (cin.get() == '\n') {
break;
}
}
int * sumOfarr1 = new int[length];
int * sumOfarr2 = new int[length];
for(int i = 0; i<length;i++){
sumOfarr1[i] = 0;
}
for(int i = 0; i<length;i++){
sumOfarr2[i] = 0;
}
int index=0;
for(int i=1;i<length;i++)
{
for(int j=0;j<Vec.size();j++)
{
if(ison(i,j))
{
sumOfarr1[index]+=Vec[j];
}
else
{
sumOfarr2[index]+=Vec[j];
}
}index++;
}
int ans=INT_MAX;
int ii;
for(int i=0;i<index;i++)
{
if(abs(sumOfarr1[i]-sumOfarr2[i])<ans)
{
ii=i;
ans=abs(sumOfarr1[i]-sumOfarr2[i]);
}
}
if(sumOfarr1[ii]<sumOfarr2[ii]){
cout << sumOfarr1[ii] << " " << sumOfarr2[ii];
}
else{
cout << sumOfarr2[ii] << " " << sumOfarr1[ii];
}
cout << endl;
delete[] sumOfarr1;
delete[] sumOfarr2;
Vec.clear();
}
return 0;
}
Yes I found the solution just using getline and stringstream.
aka this
vector<int> Vec;
string line;
while(getline( cin, line ))
{
istringstream iss( line );
int number;
while( iss >> number )
Vec.push_back(number);
}