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;
}
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"