3

Im trying to dig into this kattis.com challenge called counting stars using NodeJs. If you see the input example, it always start with a line of two integers, the first one represents the number of rows, the second one represents the numbers of columns per row, there are a lot of examples with C and Java, but I want to solve this with JS (Nodejs). How I can read from the terminal and iterate line by line, I tried with the next code

const readline = require('readline');

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

var lines = [];
rl.on('line', line => {
  lines.push(line);
  console.log(lines);
});

But for some reason, if I input this sample

3 10
#-########
----------
#-########

It only show me the first 3 lines, also tried with this line while (line = readline()) {}, but also not working because of readline isn't a function

In Java they use a class of Scanner(System.in);, and probably that class make things easier

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Yanupla
  • 31
  • 3

1 Answers1

0

You're on the right track. The missing piece is adding code to distinguish test cases. The easiest option might be to slurp all of the lines into an array, listen to "close" on the readline and then process everything synchronously in one go, chunking out tests based on the ^\d+ \d+$ pattern.

However, this approach is memory-unfriendly, so I'd prefer to only consume one test case at a time, solve it in isolation, then free the memory:

const readline = require("readline");

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

rl.on("line", line => {
    if (/^\d+ \d+$/g.test(line)) {
      if (lines.length) {
        solve(lines, id++);
        lines.length = 0;
      }
    }
    else {
      lines.push(line);
    }
  })
  .on("close", () => solve(lines, id));

let id = 1;
const lines = [];

const solve = (grid, id) => {
  let count = 0;

  // your algorithm here

  console.log(`Case ${id}: ${count}`);
};

See also:

ggorlen
  • 44,755
  • 7
  • 76
  • 106