Published
Edited
Dec 18, 2020
1 fork
1 star
Insert cell
Insert cell
function tokenize(expression) {
return expression.split(/\b|\s/).map(t => t.trim()).flatMap(t => t.match(/[()]/) ? t.split('') : t)
}
Insert cell
evaluate(rpn('1 + 2'))
Insert cell
function* rpn(expression) {
const stack = []
for (const token of tokenize(expression)) {
switch (token) {
case '(':
stack.push(token)
break
case ')':
while (stack.length) {
const n = stack.pop()
if (n === '(')
break
yield n
}
break
case '+':
case '*':
if (stack.length === 0 || stack[stack.length-1] === '(') {
stack.push(token)
} else {
while (stack.length) {
if (stack[stack.length-1] === '(')
break
yield stack.pop()
}
stack.push(token)
}
break
default: // operand
yield +token
}
}
while (stack.length)
yield stack.pop()
}
Insert cell
function evaluate(rpn) {
const stack = []
for (const token of rpn) {
switch (token) {
case '+':
stack.push(stack.pop() + stack.pop())
break
case '*':
stack.push(stack.pop() * stack.pop())
break
default:
stack.push(token)
}
}
return stack[0]
}
Insert cell
part1 = input.trim().split('\n').map(rpn).map(evaluate).reduce((sum, i) => sum + i)
Insert cell
function* rpn2(expression) {
const stack = []
for (const token of tokenize(expression)) {
switch (token) {
case '(':
stack.push(token)
break
case ')':
while (stack.length) {
const n = stack.pop()
if (n === '(')
break
yield n
}
break
case '+':
case '*':
if (stack.length === 0 || stack[stack.length-1] === '(') {
stack.push(token)
} else {
while (stack.length) {
if (stack[stack.length-1] === '(' || (token === '+' && stack[stack.length-1] === '*'))
break
yield stack.pop()
}
stack.push(token)
}
break
default: // number
yield +token
}
}
while (stack.length)
yield stack.pop()
}
Insert cell
part2 = input.trim().split('\n').map(rpn2).map(evaluate).reduce((sum, i) => sum + i)
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more