有人帮我理解在HackerRank上使用JavaScript时Node.js代码的用途吗?

我有一个编码挑战即将使用HackerRank,我不熟悉.在我开始之前,我开始尝试熟悉它,当我在编辑器中看到这个样板代码时想象我的惊喜!

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

人力资源面临的其他挑战略有修改,我不禁想知道究竟发生了什么.看起来编辑器正在读取某种文本文件,因此能够与我的输出进行比较?

我非常感谢对此的任何见解,因为我很确定在编写我的编码时我必须编写自己的Node“样板”.

谢谢!

最佳答案 代码基本上接收您需要的信息作为挑战的输入.这个特定的一个使得输入通过与挑战中描述它相同的方式来实现.

// Begin reading from stdin so the process does not exit. (basically reading from the command line)
process.stdin.resume();
//set the enconding for received data to ascii so it will be readable
process.stdin.setEncoding('ascii');


//declare variables to process the data
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

//if data is coming through, put it in the input_stdin string. keep receiving data until no more comes through
process.stdin.on('data', function (data) {
    input_stdin += data;
});

//after the transmission when the end signal is received break the string up and push each new line (\n == new line) as an element into the array.
process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

//gives you one element per line to work with.
function readLine() {
    return input_stdin_array[input_currentline++];
}

通常,此代码后面会有更多(在注释行下方),您已经获得了变量,以便将数据保存为可行的格式.

还有另一个版本的代码没有提供一口大小的块:

function processData(input) {
    //Enter your code here
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

正如您所看到的,代码基本相同,但是一些“使输入可用”的锅炉板是您必须要做的.

只是不要混淆.我在那里解决的每一个挑战,我做的第一件事是console.log(输入)或任何其他预先创建的变量.它帮助我知道实际上在哪里.

点赞