puzzle contents
Contents
raw puzzle

Original Problem

Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 11 or 22. She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting postion to the last cloud. It is always possible to win the game.

For each game, Emma will get an array of clouds numbered 00 if they are safe or 11 if they must be avoided. For example, c=[0,1,0,0,0,1,0]c=[0,1,0,0,0,1,0] indexed from 060\dots 6. The number on each cloud is its index in the list so she must avoid the clouds at indexes 11 and 55. She could follow the following two paths: 0260\rightarrow 2\rightarrow \rightarrow 6 or 023460\rightarrow 2\rightarrow 3\rightarrow 4\rightarrow 6. The first path takes 33 jumps while the second 44.

Function Description

Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer.

jumpingOnClouds has the following parameter(s):

Input Format

The first line contains an integer nn, the total number of clouds. The second line contains nn space-separated binary integers describing clouds c[i]c[i] where 0i<n0\leq i<n.

Constraints

Output Format

Print the minimum number of jumps needed to win the game.

Solution

The problem statement states that the game can always be won. Additionally, it always starts and ends with zero and does not contain any consecutive ones. So we can jump from cloud 00 to cloud n1n-1 and count every jump without additional conditions. However, if the cloud after the next one is zero, we can skip the next jump, no matter if it is one or zero and thus reduce the number of jumps. Implemented in JavaScript it can look like:

function jumpingOnClouds(c) {

  let j = 0;
  for (let i = 0; i < c.length - 1; i++, j++) {
    if (i + 2 < c.length && c[i + 2] == 0) {
      i++;
    }
  }
  return j;
}