![](/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.