Skip to content

Instantly share code, notes, and snippets.

@yamadayuki
Created December 12, 2016 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yamadayuki/b11732bea128659e4bb6701512818a87 to your computer and use it in GitHub Desktop.
Save yamadayuki/b11732bea128659e4bb6701512818a87 to your computer and use it in GitHub Desktop.
Reverse Polish notation implementation using Stack.
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_A
// Test Case
// Input
// 34 116 + 20 5 - 5 - 1 * +
// Output
// 160
var input = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split(' ').map(function(value) {
if (!isNaN(parseInt(value))) {
return parseInt(value);
} else {
return value;
}
});
function push(value, container) {
container.push(value);
return container;
}
function add(container) {
var b = container.pop();
container.push(container.pop() + b);
return container;
}
function sub(container) {
var b = container.pop();
container.push(container.pop() - b);
return container;
}
function mul(container) {
var b = container.pop();
container.push(container.pop() * b);
return container;
}
function calc(operation, container) {
switch (operation) {
case '+':
container = add(container);
break;
case '-':
container = sub(container);
break;
case '*':
container = mul(container);
}
return container;
}
var container = [];
input.forEach(function (value) {
if (typeof value === 'number') {
push(value, container);
} else {
calc(value, container);
}
});
console.log(container[0]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment