Find the starting position(s) of “runs” (consecutive characters) in the input from left to right.
Example input and output:
Input: 0000000000
Runs: 0
Input: 0101010101
Runs:
Input: 1111111111
Runs: 0
Input: 0110110110
Runs: 1 4 7
Input: 1110000011
Runs: 0 3 8
Input: 0010011010
Runs: 0 3 5
Program ended with exit code: 1
The answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
#include <iostream> using namespace std; void print_runs(const char* input) { size_t offset = 0; size_t index = 0; while(char current = input[index]) { char next = input[index + 1]; if(next && next == current) { cout << " " << offset; while(input[index] && current == input[index]) ++index; offset = index; } else { offset = ++index; } } } int main(int argv, char** argc) { const char* inputs[] = { "0000000000", "0101010101", "1111111111", "0110110110", "1110000011", "0010011010" }; for(size_t index = 0; index < (sizeof(inputs) / sizeof(*inputs)); ++index) { cout << "Input: " << inputs[index] << endl; cout << "Runs :"; print_runs(inputs[index]); cout << endl << endl; } return 1; } |