首页 > 解决方案 > 在节点中读取标准输入时面临问题

问题描述

我刚刚注册HackerEarth并尝试解决第一个基本问题:Monk and rotation. 当我通过输入单个输入来运行代码时,它工作正常,但是当我提交解决方案时它不起作用。

https://www.hackerearth.com/practice/codemonk/

It seems I am reading the input incorrectly

有人可以帮忙吗。

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 () {
    let lines = stdin_input.split('\n');
    let len = lines.length;
    let inputArr = [];
    
    const numberTestCase = lines[0]

    const output = new Array()
    
    for (i = 1; i < lines.length; i++) {
      let lineInput = lines[i].split(' ');
      let noOfElement = 0;
      let stepRotation = 0;
      let skipLineUpto = 0;
      let inputData = false;
      
      if (lineInput.length === 2) {
        inputData = true;
        noOfElement = lineInput[0]
        stepRotation = lineInput[1]

        skipLineUpto = parseInt(i) + 2;
      }
      
      if (inputData) {
        let stringOfArray = lines[i + 1];
        
        let arrayData = stringOfArray.split(' ');
        
        let mod = 0
        mod = stepRotation % noOfElement;

        if (mod != 0) {
          let unReversedArray = arrayData.splice(-mod);
          let ff = unReversedArray.concat(arrayData)
          inputArr.push(ff.join(' '))
        } else {
          let ff = arrayData
          console.log(ff.join(' '))
          inputArr.push(ff.join(' '))
        }
      }
      
    }
    main(inputArr)
});

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

标签: javascript

解决方案


当您提交时,您可以看到为什么您的代码无效。

您的解决方案适用于输入为 3 行(1 个测试用例)的场景,例如他们的示例,但您可以看到他们的测试用例有多行输入(T 测试用例)。

如果没有任何原型方法,这样的东西就可以工作(因为超过了时间而不能工作):

let lines = stdin_input.split('\n');
let loops = lines[0];

for(i = 1; i < lines.length; i+=2) {        
    let steps = lines[i].split(' ')[1];
    let arr = lines[i+1].split(' ');        
    
    for (j = 0; j < steps; j++) {
        var x = arr[arr.length-1], i;
        for (k = arr.length-1; k > 0; k--) {
            arr[k] = arr[k-1];
        }
        arr[0] = x;
    }
    
    main(arr);
}

使用pop()unshift()只有一个测试用例由于时间超过而失败,但应该让您接近最终解决方案:

let lines = stdin_input.split('\n');
let loops = lines[0];

for(i = 1; i < lines.length; i+=2) {        
    let steps = lines[i].split(' ')[1];
    let arr = lines[i+1].split(' ');        
    
    for (j = 0; j < steps; j++) {
        arr.unshift(arr.pop());
    }
    
    main(arr);
}

推荐阅读