I need to write a small map/reduce function that should return 1 if there are at least 4 continuous 0 in an array, otherwise it should return something different than 1.
Example:
[6, 7, 5, 0, 0, 0, 0, 3, 4, 0, 0, 1] => 1
[6, 7, 5, 0, 0, 0, 3, 4,0, 0, 0, 0, 0, 1] => 1
[5, 0, 0, 0, 3, 4, 0, 0, 8, 0, 0, 1] => something # 1
This is my algorithm:
[6, 7, 5, 0, 0, 0, 0, 3, 4, 0, 0, 1]
.map((i) => i === 0 ? 1 : 0)
.reduce((prev, i) => {
if (i !== 0) {
return prev + i;
} else {
if (prev >= 4) {
return 4;
}
return 0;
}
}, 0);
The .map
method will mark 0 as 1 and non-0 as zero. So [6, 7, 5, 0, 0, 0, 0, 3, 4, 0, 0, 1]
becomes [0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0]
. Then the .reduce
method will collect the number of zeroes.
If the current element is 1 (meaning zero in the input array) it returns the previous value plus the current value (1). This means it represents the number of zeroes. If the current item is 0 (meaning not 0 in the input array), it resets prev
to 0 when it is less than 4, otherwise it carries on.
At the end, if the value is 4, it means that there are at least 4 continuous 0.
The algorithm seems to run, but not meet the requirement. It requires returning 1 if the input has 4 consecutive 0, otherwise it should return any non-zero number.
Do you think of any way to do this?