Skip to content

Instantly share code, notes, and snippets.

@krtx
Created June 10, 2013 12:04
Show Gist options
  • Save krtx/5748259 to your computer and use it in GitHub Desktop.
Save krtx/5748259 to your computer and use it in GitHub Desktop.
aaaaaaaaaaaaaaaaaaaaaaaaaaaa
require 'pp'
str = 'a+b*c*(d+e)+f+g'
$idx = 0
def term(str)
ops = []
while $idx < str.length
if str[$idx] == '('
$idx += 1
ops.push(parse(str))
$idx += 1
else
ops.push(str[$idx])
$idx += 1
end
break if str[$idx] != '*'
$idx += 1
end
if ops.length == 1
return ops[0]
else
return ['*'] + ops
end
end
def parse(str)
ops = []
while $idx < str.length
if str[$idx] == '('
$idx += 1
ops.push(parse(str))
$idx += 1
else
ops.push(term(str))
end
break if str[$idx] != '+'
$idx += 1
end
if ops.length == 1
return ops[0]
else
return ['+'] + ops
end
end
pp parse('a+b*c*(d+e)+f+g')
def calc(m, tree)
if tree.class != Array
return m[tree]
end
nums = []
tree.slice(1, tree.length).each do |a|
nums.push(calc(m, a))
end
if tree[0] == '+'
return nums.reduce{|i, j| i + j}
else
return nums.reduce{|i, j| i * j}
end
end
$idx = 0
t = parse('a+b*c')
pp t
pp calc({'a' => 10, 'b' => 20, 'c' => 3}, t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment