Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module SearchMethods
- def depth(n)
- if @payload == n
- return self
- else
- @children.each do |child|
- node = child.depth(n)
- return node unless node.nil?
- end # do child end
- return nil
- end # if payload end
- end # def depth end
- def breadth(n)
- @queue = []
- @queue << self
- current_node = @queue.shift
- next_nodes = @queue.push(current_node.children)
- while !@queue.empty?
- puts "initial current node"
- p current_node # this is a tree of trees/arrays
- puts @payload unless self.nil?
- # puts current_node.children
- if current_node.payload == n
- return current_node
- else
- next_nodes = @queue.push(current_node.children)
- puts "should equal initial current node"
- p current_node # this is still a tree of trees/arrays
- current_node = @queue.shift
- puts "shifted node - should equal the 'initial current
- mode' that appears next"
- p current_node # and now it is an array of trees/ arrays
- # because it is an array, I can no longer specify
- # current_node.children (cause obvs, children isn't a
- # method) and cannot move on to the next step.
- # How do I escape this array?
- end # if payload end
- # return nil
- end # while loop end
- end # def breadth end
- end # module end
- class Tree
- attr_accessor :payload, :children
- include SearchMethods
- def initialize(payload, children)
- @payload = payload
- @children = children
- end
- end
- # The "Leafs" of a tree, elements that have no children
- deep_fifth_node = Tree.new(5, [])
- eleventh_node = Tree.new(11, [])
- fourth_node = Tree.new(4, [])
- # The "Branches" of the tree
- ninth_node = Tree.new(9, [fourth_node])
- sixth_node = Tree.new(6, [deep_fifth_node, eleventh_node])
- seventh_node = Tree.new(7, [sixth_node])
- shallow_fifth_node = Tree.new(5, [ninth_node])
- # The "Trunk" of the tree
- trunk = Tree.new(2, [seventh_node, shallow_fifth_node])
- p trunk.breadth(5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement