0

I am working on this problem in kattis where I need to get the second integer inputted on the first line. The integers can be 1-999. In the example input below, I need to display 80:

2 80
carrots
bunnies

Here is my code:

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
  
rl.on("line", (line) => {
    let inputData = line;
    console.log(inputData)
});

In the console log inputData, it displays the whole input. I also tried to split the line using let inputData = line.split(' '); and the results werebut still I don't know how to be able to get 80 :

[ '2', '80' ]
[ 'carrots' ]
[ 'bunnies' ]
Machavity
  • 30,841
  • 27
  • 92
  • 100
Janina Estrella
  • 49
  • 2
  • 10

2 Answers2

0

If its a string you can use str.split(" ") (where str is a string). You would get an array of strings like ['2','80'] from which you can access the first element.

eg:

let inputData = line.split(" ")
console.log(inputData[1]);
//output: 80
ggorlen
  • 44,755
  • 7
  • 76
  • 106
0

Basically, the question asks you to parse and print the second number from the first line (this answer shows how to split a string and pick an index), but then ignore all remaining lines.

If you don't de-register your .on("line", ...) handler, it'll throw errors or print bad output on subsequent lines.

One approach is to use .once rather than .on to de-register the handler after the first line is consumed:

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
  
rl.once("line", line => console.log(line.split(/ +/).pop()));

Now, normally with Kattis problems, you'll want to consume the rest of the data as well. See Getting input in Kattis challenges - readline js for how to do this.

ggorlen
  • 44,755
  • 7
  • 76
  • 106