See the original problem on HackerRank.
Solutions
This is an easy problem we can experiment with. The simplest solution consists in counting how many characters mismatch:
1
2
3
4
5
6
7
|
char c1, c2, c3;
auto cnt = 0;
while (cin >> c1 >> c2 >> c3)
{
cnt += (c1 != 'S') + (c2 != 'O') + (c3 != 'S');
}
cout << cnt;
|
We can use the reduce pattern:
1
2
3
4
|
static const char match[] = {'S', 'O', 'S'};
cout << accumulate(istream_iterator<char>(cin), istream_iterator<char>(), make_pair(0, 0), [](pair<int, int> s, char c) {
return make_pair(s.first + (c != match[s.second % 3]), s.second + 1);
}).first;
|
Here is a nicer solution using Linq by Simone Busoli:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
static IEnumerable<char> Sos()
{
while(true)
{
yield return 'S';
yield return 'O';
yield return 'S';
}
}
static void Main(String[] args) {
WriteLine(ReadLine().Zip(Sos(), Tuple.Create).Count(t => t.Item1 != t.Item2));
}
|
The same pattern can be used in python leveraging itertools.cycle
:
1
2
3
4
|
from itertools import cycle
def marsExploration(s):
sos = cycle('SOS')
return sum(1 for c in s if c != next(sos))
|