Last active
August 29, 2015 13:56
-
-
Save mmagm/9157670 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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