HackerRank Kangaroo Challenge with JavaScript using VS Code

I have been taking on the code challenges at HackerRank(www.hackerrank.com). I was intrigued by one named “Kangaroo” .
This was an opportunity to polish on my JavaScript coding skills. Now, how do I test a solution within Visual Studio Code (VS Code) before submission to HackerRank.
How does JavaScript access “stdin” (the input from Windows prompt) using node.js https://nodejs.org/en/ as the default compiler. After a few Googling and modification. Here is an example
on how you can use VS Code and DOS prompt to take input into JavaScript for the Kangaroo challenge.

var readline = require(‘readline’);

var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

var lines = [];

rl.on(‘line’, (line) => {
lines.push(line);
});

rl.on(‘close’, () => {

var x1 = parseInt(lines[0]);
var v1 = parseInt(lines[1]);
var x2 = parseInt(lines[2]);
var v2 = parseInt(lines[3]);

let result = ‘NO’;
for (let i = 0; i < 10000 && result == ‘NO’; i++) {
if (x1 + v1 * i == x2 + v2 * i) {
result = ‘YES’;
}
}

console.log(result);
});

You can compile your code in VS Code for visual debugging.To full run this JavsScript, use DOS prompt to test (as shown below, with 0 3 4 2 as the sample test data and “Yes” is the expected result)

C:\JavaScript\Learning>node test.js (node is the compiler for node.js)
0 <press enter>
3 <press enter>
4 <press enter>
2 <press enter>
<press ctrl-c to break the routine>
YES (The expected output for this script return by the compiler)

Hope you find this tweak useful in your learning of JavaScript and on taking the challenges at HackerRank.Com

Leave a Reply

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