I am working on a Kattis problem , where I am supposed to take the input in prefix notation, simplify it and return it in prefix notation as well.
(我正在研究Kattis 问题 ,在这里我应该以前缀表示法接受输入,将其简化并以前缀表示法返回。)
These are the examples of inputs and outputs:(这些是输入和输出的示例:)
Sample Input 1 Sample Output 1
+ 3 4 Case 1: 7
- x x Case 2: - x x
* - 6 + x -6 - - 9 6 * 0 c Case 3: * - 6 + x -6 - 3 * 0 c
I have written this piece of code, and if I run it with this kind of input data, I get exactly the same output as stated above.
(我已经编写了这段代码,并且如果使用这种输入数据运行它,我将获得与上述完全相同的输出。)
Yet, I get wrong answer from Kattis.(但是,我从Kattis那里得到了错误的答案。)
What is it that I am doing wrong here?
(我在这里做错了什么?)
It is frustrating since you get no debugging hints.(由于没有任何调试提示,这令人沮丧。)
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const operators = ['+', '-', '*', '/'];
const operatorsFunctions = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => a / b,
};
let lineNumber = 0;
rl.on('line', (line) => {
const mathExpression = line.split(' ');
lineNumber += 1;
let result = [];
let stack = [];
for (let i = mathExpression.length -1; i >= 0; i--) {
if (!isNaN(mathExpression[i])) {
stack.unshift(mathExpression[i]);
} else if (operators.includes(mathExpression[i])){
if (!stack.length) {
result.unshift(mathExpression[i]);
}
if (stack.length === 1) {
result.unshift(stack[0]);
result.unshift(mathExpression[i]);
stack = [];
}
if (stack.length > 1) {
const sum = operatorsFunctions[mathExpression[i]](Number(stack[0]), Number(stack[1]))
stack.splice(0, 2, sum);
if (i === 0) {
result.unshift(...stack);
}
}
} else {
if (stack.length) {
result.unshift(...stack);
stack = [];
}
result.unshift(mathExpression[i]);
}
}
const text = `Case ${lineNumber}: ${result.join(' ')}`;
console.log(text);
});
ask by Leff translate from so