Skip to content

Instantly share code, notes, and snippets.

@iwestlin
Last active March 6, 2022 03:04
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 iwestlin/349143b258c919be61681a666b4f3d1b to your computer and use it in GitHub Desktop.
Save iwestlin/349143b258c919be61681a666b4f3d1b to your computer and use it in GitHub Desktop.
// calc([6, 5, 2, 3, '+', 8, '*', '+', 3, '+', '*']) // 288
function calc (a) {
const stack = []
const methods = {
'+': (a, b) => b + a,
'-': (a, b) => b - a,
'*': (a, b) => b * a,
'/': (a, b) => b / a,
}
let current
while (current = a.shift()) {
if (typeof current === 'number') {
stack.push(current)
} else {
const func = methods[current]
stack.push(func(stack.pop(), stack.pop()))
}
}
console.log(stack[0])
}
function convert (mid) {
console.log(mid.join(' '))
const result = []
const stack = []
const methods = ['(', ')', '*', '/', '+', '-']
const orders = {
'*': 2,
'/': 2,
'+': 1,
'-': 1,
}
let current
while (current = mid.shift()) {
if (!methods.includes(current)) { // is number
result.push(current)
} else if (current === '(') {
stack.push(current)
} else if (current === ')') {
let t
while (t = stack.pop()) {
if (t === '(') break
result.push(t)
}
} else {
let prev
while (prev = stack.pop()) {
if (orders[prev] >= orders[current]) {
result.push(prev)
} else {
stack.push(prev)
break
}
}
stack.push(current)
}
}
let left
while (left = stack.pop()) {
result.push(left)
}
console.log(result.join(' '))
}
// convert(['a', '+', 'b', '*', 'c', '+', '(', 'd', '*', 'e', '+', 'f', ')', '*', 'g'])
// a b c * + d e * f + g * +
function Node (val, left, right) {
this.val = val
this.left = left
this.right = right
}
function totree (arr) {
const methods = ['+', '-', '*', '/']
const stack = []
let current
while (current = arr.shift()) {
if (!methods.includes(current)) { // is number
stack.push(new Node(current))
} else {
const right = stack.pop()
const left = stack.pop()
stack.push(new Node(current, left, right))
}
}
return stack.pop()
}
// console.log(JSON.stringify(totree(['a', 'b', '+', 'c', 'd', 'e', '+', '*', '*'])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment