Jumping on the Clouds HackerRank

enter image description hereI want to make a function to return an array with the number of steps it will take to finish another array but with a little condition that i want to take my steps on 0 only and that mean if i have array c = [0,0,0,1,0,0,1,0] it will take the first three 0 as one step but if i have just one 0 as you see in the end of the array it will be a step so for this array it will take 4 steps to finish it (0,0,0)(0)(0)(0) as you see it will ignore (1)

This is the link of the test if you want better description HakerRank tets link

var array = [0, 0, 0, 1, 0, 0, 1, 0]
var stepsArray = [];

function jumpingOnClouds(c) {
  for (var i = 0; i < c.length; i++) {
    if (c[i] === 0) {
      if (c[i] === c[i + 1])
        stepsArray.push(c[i + 1])
    } else {
      stepsArray.push(c[i])
    }
  }

  return stepsArray.length

}
var result = jumpingOnClouds(array);
console.log(result);

I also have tried this but it keep giving me the same error

   var array = [0, 0, 0, 1, 0, 0]
   var stepsArray = [];
   function jumpingOnClouds(c) {
    for(var i = 0; i < c.length - 1; i++){
        if (c[i] === 0) {
            console.log(c[i])
            if (c[i] === c[i + 1] && c[i + 1] === c[i + 2]) {
                stepsArray.push(c[i + 2])
            } else if (c[i] === c[i + 1]) {
                stepsArray.push(c[i + 1])
            } else {
                stepsArray.push(c[i])
            }
        }
    }
    return stepsArray.length

}
var result = jumpingOnClouds(array);
console.log(result)

Answer

Just Added 2 constraints on your solution for the index of I and removed unwanted conditions:

I tested my solution on Hackerrank:

Check this out:

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.replace(/s*$/, '')
        .split('n')
        .map(str => str.replace(/s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

// Complete the jumpingOnClouds function below.
function jumpingOnClouds(c) {

    var stepsArray = [];
   
    let i=0;
    while(i < c.length - 1){
       
        if ((i+2<c.length) && (c[i+2] === 0)) {
            stepsArray.push(c[i + 2]);
            i+=2;
        } else{
            stepsArray.push(c[i + 1]);
            i+=1;
        } 
        
    }
    return stepsArray.length

}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const n = parseInt(readLine(), 10);

    const c = readLine().split(' ').map(cTemp => parseInt(cTemp, 10));

    let result = jumpingOnClouds(c);

    ws.write(result + "n");

    ws.end();
}

Leave a Reply

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