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 \(1\) or \(2\). 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 \(0\) if they are safe or \(1\) if they must be avoided. For example, \(c=[0,1,0,0,0,1,0]\) indexed from \(0\dots 6\). The number on each cloud is its index in the list so she must avoid the clouds at indexes \(1\) and \(5\). She could follow the following two paths: \(0\rightarrow 2\rightarrow \rightarrow 6\) or \(0\rightarrow 2\rightarrow 3\rightarrow 4\rightarrow 6\). The first path takes \(3\) jumps while the second \(4\).

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 \(n\), the total number of clouds. The second line contains \(n\) space-separated binary integers describing clouds \(c[i]\) where \(0\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 \(0\) to cloud \(n-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;
}