Präfixrechner mit Stapel in Javascript

Sep 05 2020

Ich versuche, Rechner mit RPN (Reverse Polish Notation) Eingabemethode mit Stack in Javascript zu machen.

input : [1, 5, '+', 6, 3, '-', '/', 7, '*']

1 ist ein Operand, drücken Sie auf Stapel.

5 ist ein Operand, drücken Sie auf Stapel.

'+' ist ein Operator, Pop 1 und 5, berechnet sie und schiebt das Ergebnis auf Stack.

6 ist ein Operand, drücken Sie auf Stapel.

3 ist ein Operand, drücken Sie auf Stapel.

'-' ist ein Operator, Pop 6 und 3, subtrahieren sie und schieben das Ergebnis auf Stack.

'/' ist ein Operator, Pop 6 und 3, teilt sie und schiebt das Ergebnis auf Stack.

7 ist ein Operand, drücken Sie auf Stapel.

'*' ist ein Operator, Pop 2 und 7, multipliziere sie und schiebe das Ergebnis auf Stack.

output : [14]

Gibt es eine andere Alternative, um meinen Code effektiver zu machen?

const x1 = x.push(1);
const x2 = x.push(5);
const x3 = x.push('+');

x.pop(1);
x.pop(5);
x.pop('+');
x.push(1+5);

const x4 = x.push(6);
const x5 = x.push(3);
const x6 = x.push('-');

x.pop(6);
x.pop(3);
x.pop('-');
x.push(6-3);

const x7 = x.push('/');
x.pop(6);
x.pop(3);
x.pop('/');
x.push(6/3);

const x8 = x.push(7);
const x9 = x.push('*');

x.pop(2);
x.pop(7);
x.pop('*');
x.push(2*7);

console.log(x);

Antworten

3 NinaScholz Sep 05 2020 at 01:12

Sie können ein Objekt für alle Operatoren nehmen und prüfen, ob der Wert von inputein Operator ist, und dann die Operation mit den umgekehrten Popp-Werten des Stapels ausführen oder den Wert auf den Stapel verschieben.

const
    operators = {
        '+': (a, b) => a + b,
        '-': (a, b) => a - b,
        '*': (a, b) => a * b,
        '/': (a, b) => a / b
    },
    input = [1, 5, '+', 6, 3, '-', '/', 7, '*'],
    stack = [];

input.forEach(value => {
    stack.push(value in operators
        ? operators[value](...stack.splice(-2))
        : value
    );
    console.log(...stack);
});
.as-console-wrapper { max-height: 100% !important; top: 0; }