A 1D binary character array is given to you in file “task1.txt”. You are required to find out maximum
consecutive ones in the array.
Note: Read the file and find the exact length of data in a separate function. Use that size to create a
dynamic integer array using pointers. Then, read the file again and insert data into this dynamic array of
exact calculated size. Then You are required to find out maximum consecutive ones in the array.
task1.txt
11010101111110110111010
Expected output:
- maximum consecutive ones are: 111111
- Starting index is: 7
- Length is: 6
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
vector<char> a;
void init() {
ifstream in("task1.txt");
string s;
in >> s;
a.resize(s.length());
ifstream in2("task1.txt");
in2 >> s;
a.resize(s.length());
for (int i = 0; i < s.length(); i++)
a[i] = s[i];
}
int main() {
init();
int k = 0, mx = 0, ind = 0;
for (int i = 0; i < a.size(); i++)
if (a[i] == '1')
k++;
else {
if (mx < k) {
mx = k;
ind = i - k;
}
k = 0;
}
if (mx < k) {
mx = k;
ind = a.size() - k;
}
cout << "maximum consecutive ones are: " << string(mx, '1') << '\n';
cout << "Starting index is: " << ind << '\n';
cout << "Length is: " << mx;
}
Comments
Leave a comment