繁体   English   中英

如何在 Hackerrank 和 Hackerearth 中使用 Javascript?

[英]How to Use Javascript in Hackerrank and Hackerearth?

我是竞争性编程的新手。 The only language I know is Javascript but if I select javascript option I couldn't even understand how to get input and how to print output in both the sites for some problems is Hackerrank the code looks like this

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);
});

对于某些问题,在同一个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++];
}

/////////////// ignore above this line ////////////////////

function main() {
  var n = parseInt(readLine());
}

而在Hackerearth中,初始代码如下所示

   function main(input) {
        //Enter your code here
        process.stdout.write("Hello World!");
    }
    
    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);
    });
    

如果有人给我一个程序示例,如何在这些站点中获取输入并打印 output 或使用 javascript 的这些站点的任何已解决程序,我猜也可以。

让我们从 HackerEarth 举一个简单的例子: https ://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/find-factorial/

要提供解决方案,您需要执行以下操作:

function main(input) {
    //Enter your code here
    var num = parseInt(input, 10);//This line expects input to be a string so convert to an int as per problem
    var res=1;
    for(var i=num;i>1;i--) {
        res *= i; 
    }
    process.stdout.write(res);//This is how you write output.
} 

编辑:

这是在hackerrank中如何做到的:

function main() {
    var n = parseInt(readLine());
    var strN = n.toString();//<-- Convert int n to string
    for(var i=1;i<=10;i++) {
        process.stdout.write(strN+" x "+i+" = "+n*i);//<-- formatting the 
                                                     //question requires
        process.stdout.write("\n");//<-- newline
    }
}

不同之处似乎在于,在 HackerRank 中,您需要自己将输出转换为字符串。 希望能帮助到你!

编辑2

对于多行输入,例如:

5 1
1 2 3 4 1

你可以这样做:

function main(input) {
    //Enter your code here
    var data = input.split('\n');
    var firstLine = data[0].split(' ');
    var len = firstLine[0];
    //process.stdout.write('length:'+len);
    var toFind = firstLine[1];
    //process.stdout.write('toFind:'+toFind);
    //process.stdout.write('\n');
    var arr = data[1].split(' '); 
    //process.stdout.write(arr);
    for(var i=len-1;i>=0;i--) {
        if(arr[i] == toFind){
            process.stdout.write(i+1);
            return;
        }
    }
    process.stdout.write(-1);
}

请注意,输入是多行的,因此首先您需要通过执行var data = input.split('\n');将其拆分为行 . 每个拆分都会为您提供中间有空格的字符串。 因此,要获取单个字符,您必须再次拆分,但这次使用var firstLine = data[0].split(' ');类的空格 . 一旦你有了所有的输入,你就可以编写自己的算法了。 请注意,我也留下了评论,以便您知道如何在编辑器本身中进行调试。

顺便说一下,这个解决方案也可以工作并且是一个公认的解决方案。

希望这也有帮助!

让我们从 HackerEarth 举一个简单的例子:

https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/tutorial/

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){
    var data = input.split('\n');
    var num = parseInt(data[0],10);
    var str = data[1];
    process.stdout.write(num *2 + "\n" + data[1]);
    

}

样本输入:

5

你好世界

样本输出:

10

你好世界

首先我们以字符串的形式读取输入,然后我们将其转换为数组并分配给新的变量数据,这些看起来像 ["5", "helloworld"]

function main(input) {
let [first, second] = [...input.split("\n")];

 // do what ever you want here with inputs.
}

就这么简单:) 快乐编码。

// 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) {
    var data = input.split('\n');
    var firstLine = data[0].split(' ');
    var secondLine = (data[1].split(' '));
    let arr = [];
    for(let i=0;i<secondLine.length;i++){
        arr.push(parseInt(secondLine[i]));
    }
    findMininimum(arr);
    //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
function findMininimum(input){
console.log(Math.min(...input));
}

根据需要在main末尾添加process.stdout.write ,如下所示:

function myFunction(input) {
//Enter your code here
}
function main() {
//stuff
process.stdout.write(myFunction(input))
}

我最近遇到了同样的问题,并用这样的方法解决了它,希望它有所帮助:

PS:取消注释编辑器中的注释。 之后添加:

 /*Generally the Question Format is in 2 //TestCases 3 //N 1 3 5 //Array 5 3 6 11 22 12 */ /* Javascript accepts only string hence you need to parse it into integers and break the input lines */ function solve(arr){ //Code Here } function main(input){ var data = input.split('\n'); //split based on line var t = parseInt(data[0],split(' ')); //based on space var ind=0; while(ind<t){ var n = parseInt(data[2*ind+1].split(' ')); for(let i=0;i<n;i++){ var val = data[2*ind+2].split(' '); var arr=[]; for(let j=0;j<val.length;j++){ arr.push(parseInt(val[j])); } } console.log(solve(arr)); ind++; } }

在 Hackerearth 的 NodeJs 中处理二维数组输入

// Sample code to perform I/O:

// input we are taking
// 2                                        no. of test cases
// 3                                        2D array size
// 1 2 3
// 4 5 6
// 7 8 9
// 2                                        2D array size
// 4 3
// 1 4

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

process.stdin.on("data", function (input) {
    stdin_input = input.split("\n");                               // Reading input from STDIN and splitting it
});

// now the stdin_input will contain
// stdin_input = ['2', '3', '1 2 3', '4 5 6', '7 8 9', '2', '4 3', '1 4']

process.stdin.on("end", function () {
   main(stdin_input);
});
function main(input) {
    let t =parseInt(input[0]) //string -> integer | no. of test cases
    let index = 1   // we have already consumed 0th index value so we are starting from 1
    while(t--){
        // we need to increase index value each time when we consume input
        n = parseInt(input[index])
        index++
        let arr= []
        for(let i=0;i<n;i++){
            arr.push([])
            temp = input[index].split(" ")
            for(let j=0;j<n;j++){                
               arr[i].push(parseInt(temp[j]))
            }
            index++
            process.stdout.write(arr[i].toString()); // we can only print string
            process.stdout.write("\n");
        }
      
      
        // write you logic here 
      
      
        process.stdout.write("------\n");
          
    }

        
}

// output
// 1,2,3
// 4,5,6
// 7,8,9
// ------
// 4,3
// 1,4
// ------

 process.stdin.resume(); // A Readable Stream that points to a standard input stream (stdin) process.stdin.setEncoding("utf-8"); // so that the input doesn't transform let inputString1 = ""; let inputString = ""; let currentLine = 0; process.stdin.on("data", function (userInput) { inputString1 = inputString1 + userInput; // taking the input string }); process.stdin.on("end", function (x) { inputString1.trim(); inputString1 = inputString1.split("\n"); // end line for (let i = 0; i < inputString1.length; i++) { inputString += inputString1[i].trim() + " "; } inputString = inputString.split(" "); main(); }); function readline() { let result = inputString[currentLine++]; return parseInt(result); // change when you want to use strings, according to the problem } // --------------------------------------------- // use readline() to read individual integers/strings function main() { let t = readline(); for (let i = 0; i < t; i++) { let n = readline(); let arr1 = []; for (let i = 0; i < n; i++) { arr1[i] = readline(); } console.log(n,arr1) } }

**这是用于在给定测试用例数量的情况下进行输入** 2 2 2 4 3 1 2 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM