Jumping on the clouds

Overview

In this example we will see how to solve the Jumping on the clouds example mentioned in Hacker Rack in Java.

There is a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. The player can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. The player must avoid the thunderheads. Determine the minimum number of jumps it will take to jump from the starting position to the last cloud. It is always possible to win the game.

For each game, you will get an array of clouds numbered 0 if they are safe or 1 if they must be avoided.

Code

Below is the Java solution for the above mentioned problem:

public class JumpingOnTheClouds {

    public static int jumpingOnClouds(int[] c) {
        int jumps = 0, i = 0;
        while (i < c.length - 2) {
            if (c[i + 2] == 0) {
                i += 2;
            } else {
                i += 1;
            }
            jumps++;
        }
        if (i < c.length - 1) {
            return ++jumps;
        }
        return jumps;
    }
}

Test

Below is the simple test to verify the code above:

import org.junit.Test;

import static org.junit.Assert.*;

public class JumpingOnTheCloudsTest {

    @Test
    public void jumpingOnClouds() {
        assertEquals(3, JumpingOnTheClouds.jumpingOnClouds(new int[]{0, 1, 0, 0, 0, 1, 0}));
        assertEquals(4, JumpingOnTheClouds.jumpingOnClouds(new int[]{0, 0, 1, 0, 0, 1, 0}));
        assertEquals(3, JumpingOnTheClouds.jumpingOnClouds(new int[]{0, 0, 0, 0, 1, 0}));
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: