3

I'm trying to do some algorithmic problems using Node's library of read lines : readline. (Actually, It was proposed by the course).

The input code was :

var readline = require('readline');
var lineNumber = 0;

process.stdin.setEncoding('utf8');
var rl = readline.createInterface({
  input: process.stdin,
  terminal: false
});

rl.on('line', readLine);

function readLine (line) {
    // Do some work here.
}

The problem is to calculate the sum of n numbers. As input we have : 1. In the first line, the number of numbers for which we want to calculate the sum. 2. The second line will contain the "n" numbers seperated by spaces.

An example for an input would be : 5 1 4 8 7 9 The output in this case : 25

How can I do that with this library (I can do that with Java, C++, etc. But I don't know how to read multiple input lines using javascript)

1 Answer 1

4
var readline = require('readline');
var lineNumber = 0;
var NumOfNum;

process.stdin.setEncoding('utf8');
var rl = readline.createInterface({
  input: process.stdin,
  terminal: false
});

rl.on('line', readLine);
console.log("Provide number of Numbers to sum:");
function readLine (line) {
    if (lineNumber == 0) {
        if (!isNaN(parseInt(line))) {
            NumOfNum = parseInt(line);
            lineNumber++;
            console.log("Provide " + NumOfNum + " numbers sepearted by space to add: ");
        } else {
            console.log("Invalid Input");
        }
    } else {
        var sum = line.split(" ");
        if (sum.length != NumOfNum) {
            console.log("Given more/less than " + NumOfNum + " Try again");
        } else {
            sum = sum.reduce(function(a, b) {
              return (a*1) + (b*1);
            });
            console.log("Total: " + sum);
            process.exit();
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.