# Developers Planet

Stupendous February 2016

### How can I compare line from text file to multiple lines following?

I have a text file with 1s, 2s and 3s like below:

``````1
1
2
3
3
3
1
2
2
2
2
1
``````

..and I am trying to find a way to find out how many in a row for each.

For example if I was checking 1 it would output: 1 in a row: 2, 2 in a row: 1, 3 in a row: 0, 4 in a row: 0.... all the way to 20 in a row (array size), since there is 2 1s in a row once and then 2 1s by themselves (only 1 in a row)

I am trying to calculate HOW MANY TIMES the number 1 is only 1 in a row, 2 in a row, 3 in a row, etc up to 20 (if i had a longer list)

So far this is what I have, however I don't know what to do at the ??? line:

``````int main()
{
ifstream file("test.txt");
string linebuffer;
int sequenceCounts[20];
int onez = 0;

while (file && getline(file, linebuffer)){
if (linebuffer.length() == 0)continue;
{
if (linebuffer == "1")
{
??? while the next is 1->onez++
sequenceCounts[onez]++;
}
}

}
return 0;
}
``````

Anedar February 2016

Try something along the lines of this:

``````int sequenceCounts[20];
int currentOnes = 0;

while (file && getline(file, linebuffer)){
if (linebuffer.length() == 0){
if (currentOnes > 0){
sequenceCounts[currentOnes]++;
}
continue;
}

if (linebuffer == "1")
{
currentOnes++;  //We found another 1,
//meaning the current group is bigger than in the last line.
} else if (currentOnes > 0){
//This line does not contain a "1", but the previous lines did
sequenceCounts[currentOnes]++;
currentOnes = 0;
}
}
``````

Basically each time you encounter a "1" you increase a counter how long your current sequence is. When the sequence is finished (a line without a "1" but with "1"s before) you increase the counter for that particular number of "1"s and reset your counter for the current sequence.

Edit: previous failed if the file ended with a "1"

Goodies February 2016

I did this using a vector and a simple map to hold the longest consecutive streak, so you'd merely have to read the lines, parse them to ints, and add them to a vector.

``````#include <iostream>
#include <cstdlib>
#include <vector>
#include <fstream>
#include <algorithm>
#include <map>

int mostConsec(const std::vector<int> &vec) {
std::map<int, size_t> consecMap;
size_t count = 0;
int current = vec.front();
for (auto i : vec) {
if (consecMap.count(current) == 0)
consecMap[current] = 0;
if (i == current) {
count += 1;
if (consecMap[current] <= count)
consecMap[current] = count;
}
else {
count = 1;
}
current = i;
}
auto ptr = std::max_element(
consecMap.begin(),
consecMap.end(),
[](const std::pair<int, size_t> &p1, const std::pair<int, size_t> &p2) {return p1.second < p2.second; }
);
return ptr->first;
}

int main(int argc, char **argv) {
std::vector<int> v;
std::ifstream inFile("test.txt");
int tmp;
while (inFile >> tmp)
v.push_back(tmp);
inFile.close();
int most = mostConsec(v);
std::cout << most << std::endl;
system("pause");
}
``````