12
Jan
2020

Hackerrank Jumping on the Clouds (Javascript)

Javascript :

function jumpingOnClouds(c) {
    var noOfJumps = 0, i = 2;
    if(c.length == 2){
        noOfJumps = 1;
    }
    while(i < c.length){
         if (c[i] == 1) {
            //cannot jump
            i--;
        } else{
            if(i + 2 < c.length){
                noOfJumps++;
                i+=2;
            }else{
                noOfJumps++;
                i++;
            }      
        }
    }
    return noOfJumps;
}

Explanation:

The first if statement takes care of the corner case of 2 elements in c, such that it will always at least have 1 jump (actually, a do while loop may be more suitable than a while loop here since that is the case.)

Next, for the entire of the c array, take the maximum length we could possibly jump (+2), and check if we can jump there. If unable (1 means unable to jump, 0 means able to jump), jump to the next possible jumping spot (+1), add 1 to noOfJumps, and check for the next highest possible jump height (+2) again. However, if the next +2 jump is out of bounds of the array(end of the array), add 1 to noOfJumps instead and exit the jumping session by adding 1 to i, so i becomes equal to c.length, exiting the loop.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *