Search code examples
javascriptnode.jssplitreadline

How to line split in Kattis problem-solving?


I am currently doing some tests at Kattis and I'm stuck with this one. The code I have written until now gives me the last else statement when console.logging in Visual Studio code. If I type a number below 100 it gives me the first if statement however Kattis only gives me errors. Where does the problem lie here?

I am using JavaScript (Nodejs).

Below is the code I am working on:

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

rl.on('line', (line) => {
    var n = line.split(' ');
    for (var i = 0; i < n.length; i++) {
        var r = parseInt(n[i][0]);
        var e = parseInt(n[i][1]);
        var c = parseInt(n[i][2]);
        if (r > e - c) {
            console.log("do not advertise");
        }
        else if (r < e - c) {
            console.log("advertise");
        } else {
            console.log("does not matter");
        }
    }
}); 

Solution

  • You could take a flag for getting the first line and if you got the line number, just split the line for getting the values.

    const readline = require('readline')
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    
    var first = true;
    
    rl.on('line', (line) => {
        if (first) {
            n = +line;
            first = false;
            return;
        }
        if (!n || !n--) return; // exit early for not needed lines
    
        var [r, e, c] = line.split(' ').map(Number); // take numbers
    
        if (r > e - c) {
            console.log("do not advertise");
        } else if (r < e - c) {
            console.log("advertise");
        } else {
            console.log("does not matter");
        }
    });