Skip to content

Instantly share code, notes, and snippets.

@olegon
Created September 1, 2016 18:19
Show Gist options
  • Save olegon/3826d193cffb8c367e0deefe3a5b0c61 to your computer and use it in GitHub Desktop.
Save olegon/3826d193cffb8c367e0deefe3a5b0c61 to your computer and use it in GitHub Desktop.
Esse programa foi feito para transformar expressões da notação infixa para a pós-fixada (polonesa inversa) e vice-versa.
"use strict";
/*
Esse programa foi feito para transformar expressões da notação infixa para a pós-fixada (polonesa inversa) e vice-versa.
*/
function infixToPosfix (infixExpression) {
const postfixExpression = []
const operators = []
for (const char of infixExpression) {
if (['(', ' '].includes(char)) {
continue
}
else if (char == ')') {
if (operators.length < 1) {
throw new Error('A expressão é mal-formada.')
}
postfixExpression.push(operators.pop())
}
else if (['+', '-', '*', '/'].includes(char)) {
operators.push(char)
}
else {
postfixExpression.push(char)
}
}
return postfixExpression.join('')
}
function postfixToInfix (postfixExpression) {
const operands = []
for (const char of postfixExpression) {
if (['(', ')', ' '].includes(char)) {
continue
}
else if (['+', '-', '*', '/'].includes(char)) {
if (operands.length < 2) {
throw new Error('A expressão é mal-formada.')
}
const rightOperand = operands.pop()
const leftOperand = operands.pop()
operands.push(`(${leftOperand} ${char} ${rightOperand})`)
}
else {
operands.push(char)
}
}
return operands.pop()
}
const infixExpressions = [
'(((((a+b)+c)+(d /e))-(f*g))-h)',
'(((a+b)+((c+d)/e))-(f*(g-h)))'
]
const postfixExpressions = [
'abc+-de*/fgh--*',
'abc*/'
]
infixExpressions.forEach(expression => console.log(infixToPosfix(expression)))
postfixExpressions.forEach(expression => console.log(postfixToInfix(expression)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment