i am trying to solve this problem (https://www.hackerrank.com/challenges/service-lane). i write a code
'use strict';
function processData(input) {
var lines = input.split('\n');
var nFreeLane = lines[0].split(' ')[0];
var nTestCase = lines[0].split(' ')[1];
nFreeLane = parseInt(nFreeLane);
nTestCase = parseInt(nTestCase);
var nFreeWidth = lines[1].split(' ').map(function(num) {
return parseInt(num);
});
for (var i = 2; i < nTestCase + 2; i++) {
var xx = lines[i].split(' ');
var entryPoint = xx[0];
var exitPoint = xx[1];
var nAr;
if (exitPoint == nFreeWidth.length - 1) {
nAr = nFreeWidth.slice(entryPoint);
} else {
console.log('coming here');
console.log('exit point is' + exitPoint);
console.log(nFreeWidth.length);
nAr = nFreeWidth.slice(entryPoint, exitPoint + 1);
console.log('nAr is' + nAr);
}
if (Math.min.apply(null, nAr) >= 3) process.stdout.write('3\n');
if (Math.min.apply(null, nAr) == 2) process.stdout.write('2\n');
if (Math.min.apply(null, nAr) == 1) process.stdout.write('1\n');
}
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
var _input = "";
process.stdin.on("data", function(input) {
_input += input;
});
process.stdin.on("end", function() {
processData(_input);
});
when i run this code for input
5 5
1 2 2 2 1
2 3
1 4
2 4
2 4
2 3
expected output is
2
1
1
1
2
but my output is
1
1
1
1
1
when i use slice method for
if (exitPoint == nFreeWidth.length - 1) {
nAr = nFreeWidth.slice(entryPoint);
} else {
console.log('coming here');
console.log('exit point is' + exitPoint);
console.log(nFreeWidth.length);
nAr = nFreeWidth.slice(entryPoint, exitPoint + 1);
console.log('nAr is' + nAr);
}
nAr is giving for 2,3 is [2,2,1] but expected is [2,2] .can any one please tell why its showing this behaviour.Please explain.Thanks
Your
var exitPoint = xx[1];
is a string. When you do exitPoint + 1
in
nAr = nFreeWidth.slice(entryPoint, exitPoint + 1);
you are actually doing a string concatenation: "2"+1 == "21"
. slice
will accept that (convert it into a number) gladly and return an array which is an order of magnitude too long…
Here's a fixed, simplified and working version of your code:
function processData(input) {
var lines = input.split('\n');
lines.shift(); // uninteresting stats, might simplify parsing in other languages
var widths = lines.shift().split(' ').map(Number);
// console.log("passed widths: ", widths.length);
for (var i = 0; i < lines.length; i++) {
var parts = lines[i].split(' ');
var entryPoint = +parts[0]; // "+" casts to number
var exitPoint = +parts[1];
// console.log('in: '+entryPoint+', out: ' + exitPoint);
var sectionWidths = widths.slice(entryPoint, exitPoint + 1);
// console.log('sections is ' + sectionWidths);
var minWidth = Math.min.apply(null, sectionWidths);
process.stdout.write(Math.min(minWidth, 3)+'\n');
}
}