Saturday, January 26, 2019

Jumping on the Clouds - Hacker Rank Solution

Jumping on the Clouds  -  Hacker Rank Solution

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  or . 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  if they are safe or  if they must be avoided. For example,  indexed from . The number on each cloud is its index in the list so she must avoid the clouds at indexes  and . She could follow the following two paths:  or . The first path takes jumps while the second takes .
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):
  • c: an array of binary integers
Input Format
The first line contains an integer , the total number of clouds. The second line contains  space-separated binary integers describing clouds  where .
Constraints
Output Format
Print the minimum number of jumps needed to win the game.
Sample Input 0
7
0 0 1 0 0 1 0
Sample Output 0
4
Explanation 0: 
Emma must avoid  and . She can win the game with a minimum of  jumps:
Sample Input 1
6
0 0 0 0 1 0
Sample Output 1
3
Explanation 1: 
The only thundercloud to avoid is . Emma can win the game in  jumps:

Jumping on the Clouds  -  Hacker Rank Solution

This is a simulation problem. Because the problem guarantees that it is always possible to win, we know that our input will never contain  consecutive thunderclouds. To reach the last cloud in a minimum number of steps, always try make a jump from  to . If that is not possible, jump to .
The Problem Setter's solution below uses this approach. Check out the Problem Tester's solution for a slightly different approach.

Python 2

n = int(raw_input())
c = map(int, raw_input().split(" "))
ans = 0
i = 0
while i < n - 1:
    if i + 2 >= n or c[i + 2] == 1:   # Not possible to make a jump of size 2
        i = i + 1
        ans = ans + 1
    else:
        i = i + 2
        ans = ans + 1
print ans

Ruby

#!/bin/ruby

n = gets.strip.to_i
c = gets.strip
c = c.split(' ').map(&:to_i)
ans = 0
i = 0
while i < n - 1
    (i + 2 >= n or c[i + 2] == 1 )? i=i+1: i=i+2
    ans = ans + 1
end
print ans

C++

#include <bits/stdc++.h>
using namespace std;

const int inf = 555;
int A[111], dp[111];

int main() {
    int n; cin >> n;

    for(int i=1; i<=n; i++) {
        cin >> A[i];
    }
    for(int i=2; i<=n; i++) {
        if(A[i] == 0) dp[i] = min(dp[i-1], dp[i-2]) + 1;
        else dp[i] = inf;
    }
    cout << dp[n] << "\n";
    return 0;
}

25 comments:

  1. JavaScript:

    function jumpingOnClouds(c) {
    var jumpCount = 0;
    let step = 0;
    for(let i=0; i<c.length; i){
    if(c[i] === 0 && i !== (c.length - 2)){
    i = i + 2;
    jumpCount++
    } else if (c[i] === 0 && i === (c.length - 2)){
    i = i + 1;
    jumpCount++
    } else {
    i = i - 1;
    }
    }
    return jumpCount - 1;
    }

    ReplyDelete
  2. its not working properly for all test cases

    ReplyDelete
    Replies
    1. Yes. A better solution can be found here. https://www.thepoorcoder.com/hackerrank-jumping-on-the-clouds-solution/

      Delete
    2. #include
      int main()
      {
      int n,k,i,energy=100,count=0,j=0;
      int arr[100];
      scanf("%d%d",&n,&k);
      for(i=0;in)
      {
      j=k-((n-j)+1);
      count=1;
      }
      else if(j==n)
      j=k;
      else
      j=j+k;

      if(arr[j]==0)
      energy=energy-1;
      if(arr[j]==1)
      energy=energy-3;
      if(j==0 && count==1)
      {
      break;
      }
      }
      printf("%d",energy);
      }

      Delete
    3. It is not appearing even though we write the full library name. i also tried.

      Delete
  3. JavaScript:

    function jumpingOnClouds(c){
    let numOfJumps = 0;

    for(let i = 0; i < c.length; i++){
    if(c[i] === 0 && c[i + 2] === 0){
    numOfJumps = numOfJumps + 1;
    i = i + 1;
    continue;
    }
    if(c[i] === 0 && c[i+1] === 0 && c[i+2] === 1){
    numOfJumps = numOfJumps + 1;
    continue;
    }
    if(c[i] === 0 && c[i+1] === 0 && !c[i+2]){
    numOfJumps = numOfJumps + 1;
    continue;
    }
    }

    return numOfJumps;
    }

    ReplyDelete
  4. package main

    import (
    "fmt"
    "strconv"
    )

    func main() {
    fmt.Println("Hello, playground")

    data := jumpingOnClouds([]int32{0, 0, 1, 0, 0, 1, 0})

    fmt.Println("data", data)
    }

    func jumpingOnClouds(c []int32) int32 {

    var data int32 = 1
    //fmt.Println(c)

    steps := "0"
    i := 0
    for j := 0; j < len(c); j++ {

    //fmt.Println("i===", i)
    nextelem := i + (1)
    nexttonext := i + (2)

    if len(c) > nexttonext && c[nexttonext] != 1 {

    //fmt.Println("=========", nexttonext, "c[nexttonext]", c[nexttonext])
    steps += "-ntn-" + strconv.Itoa(nexttonext)

    i = nexttonext
    data = data + 1
    } else if len(c) > nextelem {
    steps += "-ne-" + strconv.Itoa(nextelem)
    i = nextelem
    data = data + 1
    }

    if i >= len(c) {
    break
    }
    }

    fmt.Println("steps", steps)

    return data
    }

    ReplyDelete
  5. JAVA

    static int jumpingOnClouds(int[] c) {
    int i;
    int jump=0;

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

    }

    ReplyDelete
    Replies
    1. In for loop condition it must be i<c.length itself not c.length-1

      Delete
    2. Change for loop as i<c.length and return jump-2, will pass all TC

      Delete
    3. why are we running loop c.length-1 time? y is it giving error in i<c.length plz explain

      Delete
    4. c.length would work for an array, but this is an ArrayList and must be used like this c.size()

      Similarly c[i] wont work, you must do c.get(i)

      Delete
  6. #include
    #include
    using namespace std;
    int main()
    {
    int i,v,n;
    int count=0;
    vector c;
    cout<<"\nEnter the number of elements in the vector"<>n;
    for(i=0;i>v;
    c.push_back(v);
    }
    cout<<endl;
    int jump=0;
    for(i=0;i<c.size();)
    {
    if(c.size()==1 || c.size()==0)
    {
    cout<<jump<<endl;
    exit(0);
    }
    else if(c[i]==0 && c[i+1]==0 && c[i+2]==0)
    {
    jump=jump+1;
    c.erase(c.begin());
    c.erase(c.begin());
    cout<<"case 1"<<endl;
    }
    else if( c[i]==0 && c[i+1]==1)
    {
    jump=jump+1;
    c.erase(c.begin());
    c.erase(c.begin());
    cout<<"case 2"<<endl;
    }
    else if(c[i]==0 && (c[i+1]==0 || c.size()==1||c.size()==2) && (c[i+2]==1||c.size()==1||c.size()==2))
    {
    jump=jump+1;
    c.erase(c.begin());
    cout<<"case 3"<<endl;
    }

    }
    cout<< jump << endl;
    }

    ReplyDelete
    Replies
    1. # include which library functions we should use

      Delete
  7. for python 3
    We use list(map...)

    ReplyDelete
  8. Java code:


    import java.io.*;
    import java.math.*;
    import java.security.*;
    import java.text.*;
    import java.util.*;
    import java.util.concurrent.*;
    import java.util.regex.*;

    public class Solution {

    // Complete the jumpingOnClouds function below.
    static int jumpingOnClouds(int[] c) {
    int n = c.length;
    int i=0;
    int jump=0;
    while(i<n-1){
    if(i+2<n && c[i+2]==0){
    i=i+2;
    jump++;
    }
    else if(c[i+1]==0){
    i++;
    jump++;
    }
    else i++;
    }
    return jump;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

    int n = scanner.nextInt();
    scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

    int[] c = new int[n];

    String[] cItems = scanner.nextLine().split(" ");
    scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

    for (int i = 0; i < n; i++) {
    int cItem = Integer.parseInt(cItems[i]);
    c[i] = cItem;
    }

    int result = jumpingOnClouds(c);

    bufferedWriter.write(String.valueOf(result));
    bufferedWriter.newLine();

    bufferedWriter.close();

    scanner.close();
    }
    }

    ReplyDelete
  9. C# Code:

    static int jumpingOnClouds(int[] c) {
    int i=0;
    int steps=0;
    int size=c.Count();
    while(i<size)
    {
    if(c[0]==1)
    {
    if(c[2]!=1) i+=2;
    else i+=1;
    steps+=1;
    }
    else
    {
    if(i==size-1)
    {
    break;
    }
    else if(i==size-2 || i==size-3)
    {
    steps+=1;
    break;
    }
    else
    {
    if(c[i+2]!=1)
    {
    i+=2;
    steps+=1;
    }
    else
    {
    i+=1;
    steps+=1;
    }
    }
    }
    }
    return steps;
    }

    ReplyDelete
  10. n = int(input())
    c = list(map(int, input().split(" ")))
    ans = 0
    i = 0
    while i < n - 1:
    if i + 2 >= n or c[i + 2] == 1: # Not possible to make a jump of size 2
    i = i + 1
    ans = ans + 1
    else:
    i = i + 2
    ans = ans + 1
    print(ans)

    ReplyDelete
  11. i think there should e less than sign at i+2 >=n

    ReplyDelete
  12. Easy JS solution

    function jumpingOnClouds(c) {
    let minJumps = 0;
    let currPos = 0;
    for(let i = 0; i < c.length; i++) {
    const oneJump = c[currPos + 1];
    const twoJump = c[currPos + 2];

    if(twoJump === 0) {
    currPos += 2;
    minJumps++;
    } else if(oneJump === 0) {
    currPos += 1;
    minJumps++;
    }

    }
    return minJumps;
    }

    ReplyDelete
  13. Here is my solution

    function jumpingOnClouds(c) {
    // Write your code here
    let jumps = 0;
    let count = 0
    for (let i=0; i < c.length; i++) {
    if(c[i] === 0) {
    if (count === 1) {
    jumps ++;
    count = 0
    } else {
    count ++;
    }
    } else {
    if(c[i + 1] === 0) {
    jumps ++;
    count = 0;
    }
    }
    }
    return jumps;
    }

    ReplyDelete

  14. C# CODE


    using System.CodeDom.Compiler;
    using System.Collections.Generic;
    using System.Collections;
    using System.ComponentModel;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Runtime.Serialization;
    using System.Text.RegularExpressions;
    using System.Text;
    using System;
    class Result
    {

    public static int jumpingOnClouds(List c)
    {
    int jumpCount = 0;
    int step = 0;
    for(int i=0; i c = Console.ReadLine().TrimEnd().Split(' ').ToList().Select(cTemp => Convert.ToInt32(cTemp)).ToList();

    int result = Result.jumpingOnClouds(c);

    textWriter.WriteLine(result);

    textWriter.Flush();
    textWriter.Close();
    }
    }

    ReplyDelete

Powered by Blogger.