javascript - 在节点中读取标准输入时面临问题
问题描述
我刚刚注册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
}
解决方案
当您提交时,您可以看到为什么您的代码无效。
您的解决方案适用于输入为 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);
}
推荐阅读
- c# - 无法从 OnGet 方法获取 id
- f# - 在 F# 中实现 List.scani 的好方法是什么?
- c - 在链表中插入节点时递归如何工作?
- javascript - 将动态标题传递给 reactjs 中的 HOC 常用函数
- vb.net - 将多个选定的 DataGridView 行写入 CSV
- regex - 如何使用 unix/linux grep/awk/sed 从文件中输出带有空格的段落
- postgresql - Docker 无法在 Centos 8 上构建 PostgreSQL 12
- .htaccess - 将 RewriteBase 从 htaccess 移动到站点 conf 不起作用
- python - NumPy - 从 3D 数组中排除所有零 2D 数组
- postgresql - 我们究竟将这个 postgresql.conf 配置文件放在 Spring Boot 应用程序中的什么位置?