Skip to content

Instantly share code, notes, and snippets.

@getaclue00
Created October 3, 2018 17:02
Show Gist options
  • Save getaclue00/5ba6f56923a96e6b3318171b6fd10069 to your computer and use it in GitHub Desktop.
Save getaclue00/5ba6f56923a96e6b3318171b6fd10069 to your computer and use it in GitHub Desktop.
Reverse Polish notation
var input = `15 7 1 1 + − ÷ 3 × 2 1 1 + + −`
var processed_input = input.split(' ')
function RPN() {
var stack = [];
var f = function() {
};
f.size = function() {
return stack.length;
}
f.exe = function(v) {
if (v === '+') {
var res = stack.pop() + stack.pop();
stack.push(res);
return;
}
if (v === '*') {
var res = stack.pop() * stack.pop();
stack.push(res);
return;
}
if (v === '-') {
var res = stack.pop() - stack.pop();
stack.push(res);
return;
}
if (v === '/') {
var res = stack.pop() / stack.pop();
stack.push(res);
return;
}
if (v === '=') {
return stack.pop();
}
stack.push(v);
};
return f;
}
var input = `15 7 1 1 + - / 3 * 2 1 1 + + -`
function MathSolver() {
this.solvePostfix = function(postfix) {
var resultStack = [];
postfix = postfix.split(" ");
for(var i = 0; i < postfix.length; i++) {
if(postfix[i].isNumeric()) {
resultStack.push(postfix[i]);
} else {
var a = resultStack.pop();
var b = resultStack.pop();
if(postfix[i] === "+") {
resultStack.push(`${parseInt(a) + parseInt(b)}`);
} else if(postfix[i] === "-") {
resultStack.push(`${parseInt(b) - parseInt(a)}`);
} else if(postfix[i] === "*") {
resultStack.push(`${parseInt(a) * parseInt(b)}`);
} else if(postfix[i] === "/") {
resultStack.push(`${parseInt(b) / parseInt(a)}`);
} else if(postfix[i] === "^") {
resultStack.push(`${Math.pow(parseInt(b), parseInt(a))}`);
}
}
}
if(resultStack.length > 1) {
return "error";
} else {
return resultStack.pop();
}
}
}
// =======================================================
String.prototype.isNumeric = function() {
return !isNaN(parseFloat(this)) && isFinite(this);
}
this.solvePostfix = function(postfix) {
var resultStack = [];
postfix = postfix.split(" ");
for(var i = 0; i < postfix.length; i++) {
if(postfix[i].isNumeric()) {
resultStack.push(postfix[i]);
} else {
var a = resultStack.pop();
var b = resultStack.pop();
if(postfix[i] === "+") {
resultStack.push(parseInt(a) + parseInt(b));
} else if(postfix[i] === "-") {
resultStack.push(parseInt(b) - parseInt(a));
} else if(postfix[i] === "*") {
resultStack.push(parseInt(a) * parseInt(b));
} else if(postfix[i] === "/") {
resultStack.push(parseInt(b) / parseInt(a));
} else if(postfix[i] === "^") {
resultStack.push(Math.pow(parseInt(b), parseInt(a)));
}
}
}
if(resultStack.length > 1) {
return "error";
} else {
// return resultStack.pop();
return resultStack;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment