Skip to content

Instantly share code, notes, and snippets.

@mmagm
Last active August 29, 2015 13:56
Show Gist options
  • Save mmagm/9157670 to your computer and use it in GitHub Desktop.
Save mmagm/9157670 to your computer and use it in GitHub Desktop.
class Node
attr_accessor :numbers
attr_accessor :children
def initialize
@numbers = []
@children = []
end
end
class Tree
include Enumerable
def initialize(str)
@root = build(str)
end
def each
queue = Array(@root)
while !queue.empty?
node, *queue = queue
yield node.numbers
node.children.each do |sub|
queue.push sub
end
end
end
private
def build(str)
root = nil
stack = []
str.each do |token|
if token == '['
node = Node.new
parent = stack.last
parent.children << node unless parent.nil?
stack.push node
elsif integer?(token)
node = stack.last
node.numbers << token.to_i
else
root = stack.pop
end
end
root
end
def integer?(str)
/\A[+-]?\d+\z/ === str
end
end
tree_str = ['[','1','[','2','3',']','4','[','5','[','6','7',']',']','[','8',']',']']
tree = Tree.new(tree_str)
tree.each { |numbers| puts numbers.reduce(&:+) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment