As an exercise to learn Java 8+ Streams I wanted to cast some of my simple Codility implementations as a Stream solution.
For example, the BinaryGap problem .. a simple one liner solution using Streams could be something like:
public static int solution(int N) {
return Integer.toBinaryString(N).chars().
filter(x -> x == '1').whichIndexes().diff().max();
}
Only problem though, whichIndexes
and diff
don't exist. I need a way to get hold of the index of the filtered elements and then compute their pair-wise differences and that'd be a good starting point for a Streams' based one-liner solution.
UPDATE: here is my BinaryGap solution in C++, the Java non-Stream-ed version would be very similar though:
#include <bitset>
#include <iostream>
#include <math.h>
using namespace std;
int solution(int N) {
bitset<32> bs(N);
int maxGap = 0;
std::size_t i = 0;
while (bs[i] == 0) {
i++;
}
int startPos = i;
for (; i < bs.size(); ++i) {
if (bs[i] == 1) {
int gap = i - startPos - 1;
if (gap > maxGap) {
maxGap = gap;
}
startPos = i;
}
}
return maxGap;
}
int main() {
cout << solution(9) << " must be 2" << endl;
cout << solution(529) << " must be 4" << endl;
cout << solution(20) << " must be 1" << endl;
cout << solution(32) << " must be 0" << endl;
cout << solution(1041) << " must be 5" << endl;
return 0;
}