![](/img/trans.png)
[英]Can someone explain how the reduce method is working in this Functional JavaScript challenge?
[英]Sibice challenge open Kattis JavaScript not working
我正在学习JavaScript,朋友推荐打开Kattis解决任务。 (我现在知道它可能不是 JS 的最佳选择)。
不管怎样,我正在做这个Sibice挑战,你要检查火柴是否适合一个盒子。 阅读上下文链接的挑战。
我正在解决问题,但我没有通过 Kattis 针对该问题进行的任何测试。 我使用readline
获取输入,因为您需要在打开的 Kattis 中从终端获取输入。
附件是我的代码。 对不起,如果它很乱(也会接受提示哈哈),你有什么想法吗? 这也是我的第一个问题,如果我没有完美提交,我深表歉意!
这是我的代码,当我运行它时,它工作正常。 但卡蒂斯不接受。
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question(
"Enter the number of matches and the width and height of the box, separated by spaces: ",
input => {
const [numMatches, width, height] = input
.split(" ")
.map(Number);
const length = Math.sqrt(width * width + height * height);
const matchLengths = [];
const matchArray = () => {
return new Promise(resolve => {
rl.question("match length?", matchLength => {
matchLengths.push(matchLength);
resolve();
});
});
};
const askQuestion = async numMatches => {
for (i = 0; i < numMatches; i++) {
await matchArray();
}
rl.close();
};
askQuestion(numMatches).then(() => {
matchLengths.forEach(element => {
console.log(element <= length ? "DA" : "NE");
});
});
},
);
避免rl.question
,它打印标准输出的提示,即 Kattis 正在查看的 stream 以确定您的程序是否正确。 您的程序应该完全静默,除了打印预期的确切 output,仅此而已。 扼杀你的用户体验直觉,专注于算法。
我通常推荐以下方法来解决 JS 中的 Kattis 问题:
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.once("line", line => {
// process preamble
rl.on("line", line => {
// process line
});
rl.on("close", () => {
// print result of computation that requires all lines
});
});
然而,对于这个问题,每个测试用例都可以在每一行之后计算和打印,所以你可以跳过关闭监听器和数组:
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.once("line", line => {
const [n, w, h] = line.split(" ").map(Number);
const length = Math.sqrt(w * w + h * h);
rl.on("line", line => console.log(line > length ? "NE" : "DA"));
});
如果你真的想使用承诺,这也被接受:
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const read = () => new Promise(r => rl.once("line", line => r(line)));
(async () => {
const [n, w, h] = (await read()).split(" ").map(Number);
const length = Math.sqrt(w * w + h * h);
for (let i = 0; i < n; i++) {
console.log((await read()) > length ? "NE" : "DA");
}
})();
也就是说,我依稀记得在其他 Kattis 问题上遇到过 promisification 的问题,而且 promises 似乎并没有提供太多的优雅提升,所以我会坚持使用简单的回调。
顺便说一句,您的for (i = 0; i < numMatches; i++) {
应该使用let i
以避免引入容易导致错误的全局范围变量。
也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.