HackerEarth:如何从 STDIN 读取并写入 STDOUT?

HackerEarth: How to read from STDIN and write to STDOUT?

这里有人在 HackerEarth 上解决问题吗?我对他们提供输入数据的方式感到困惑。

到目前为止,我一直在使用 Leetcode 来解决问题,我对它们非常满意,但不幸的是,有些人更喜欢 HackerEarth 来举办编码挑战,而我在尝试正确阅读输入测试用例时遇到了问题。

以此为例:https://www.hackerearth.com/practice/algorithms/searching/ternary-search/practice-problems/algorithm/small-factorials/submissions/

我做了研究,发现他们的“解决方案指南”有错误的信息:https://www.hackerearth.com/docs/wiki/developers/solution-guide/

在JS(Node v10)中如何判断读取各个行并输出结果?

谢谢。

  • 刚刚登录并查看了 here

  • 好像和我不太喜欢的HackerRank差不多。 (LeetCode 的 UI 很有趣而且更容易使用。)

  • 在 LeetCode 上,我们不必打印出来,这里似乎我们必须打印输出(例如在 JavaScript 中我们会使用 console.log 而不是提到在方法内部打印通常是一种糟糕的编码实践。

这个解决方案(从其中一个活动中复制)似乎通过了,您可以根据它来解决问题:


/*
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {
    process.stdout.write("Hi, " + input + ".\n");       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
*/

// Write your code here


process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data", function (input) {
    stdin_input += input;
});
process.stdin.on("end", function () {
   main(stdin_input);
});
function main(input) {
    input = input.split('\n');
    input.shift();
    input.forEach(n => {
        n = parseInt(n);
        let fact = BigInt(1);
        while(n){
            fact = BigInt(fact) * BigInt(n);
            n--;
        }
        console.log(String(fact).replace('n',''));
    });
}

与 leetcode 和 Hacker Rank 相比,HackerEarth 的访问输入有点不同,您必须按行号从标准输入 (STDIN) 中提取输入,您可以找到更多详细信息 here

例如,如果输入的格式如下
输入格式:
第一行包含整数 N。
第二行包含字符串 S.

然后您将用新行(“\n”)拆分 STDIN 并逐行访问每个输入

下面是您将如何访问 JavaScript

中的输入的示例
var input1 = 0;
var input2 = "";
var stdin_input = ""
process.stdin.on("data", function (input) {
    // Reading input from STDIN
    stdin_input += input;  
    input1 = stdin_input.split("\n")[0] 
    input2 = stdin_input.split("\n")[1]

    console.log("input1 = ", input1)
    console.log("input2 = ", input2)
                       
                             
});