Last active
November 1, 2016 18:29
-
-
Save alexcorre/d7c74577d451edaaff87347a0149f773 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Challenge: Write a function that checks if all the zeros of an array are at the | |
end (an array with no zeros in it does have all its zeros at the end). An empty | |
array also has all its zeros at the end. | |
The function should run in O(n) time, and it's okay if it always runs in O(n). | |
The objective here is "elegance" (ease of reading the code), not | |
performance. | |
Inspired by this real world Ruby discussion: | |
https://github.com/thewca/worldcubeassociation.org/pull/978/files#r85463024 | |
*/ | |
function areZerosAtEnd(arr) { | |
let zeroSeen = false; | |
return arr.reduce((validSoFar, currentValue) => { | |
const isZero = currentValue === 0; | |
zeroSeen = zeroSeen || isZero; | |
return validSoFar && (isZero || !zeroSeen); | |
}, true); | |
} | |
console.assert(areZerosAtEnd([1,1,1,1,1]) === true, 'all non-zero should be true'); | |
console.assert(areZerosAtEnd([1,1,1,1,0]) === true, 'one zero at the end should be true'); | |
console.assert(areZerosAtEnd([0,0,0]) === true, 'all zeros should be true'); | |
console.assert(areZerosAtEnd([2,0,0,0,0]) === true, 'a number with all zeros at the end should be true'); | |
console.assert(areZerosAtEnd([0,0,0,2,0]) === false, 'should be false. there are zeros after a non-zero.'); | |
console.assert(areZerosAtEnd([2,0,0,0,2,0]) === false, 'should be false. there is a zero after a non-zero'); | |
console.assert(areZerosAtEnd([19,0,0,0,2,0,0]) === false, 'should be false. there are multiple zeros after a non-zero'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment