Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. module SearchMethods
  2. def depth(n)
  3. if @payload == n
  4. return self
  5. else
  6. @children.each do |child|
  7. node = child.depth(n)
  8. return node unless node.nil?
  9. end # do child end
  10. return nil
  11. end # if payload end
  12. end # def depth end
  13.  
  14. def breadth(n)
  15. @queue = []
  16. @queue << self
  17. current_node = @queue.shift
  18. next_nodes = @queue.push(current_node.children)
  19.  
  20. while !@queue.empty?
  21.  
  22. puts "initial current node"
  23. p current_node # this is a tree of trees/arrays
  24. puts @payload unless self.nil?
  25. # puts current_node.children
  26. if current_node.payload == n
  27. return current_node
  28. else
  29. next_nodes = @queue.push(current_node.children)
  30. puts "should equal initial current node"
  31. p current_node # this is still a tree of trees/arrays
  32.  
  33. current_node = @queue.shift
  34. puts "shifted node - should equal the 'initial current
  35. mode' that appears next"
  36. p current_node # and now it is an array of trees/ arrays
  37. # because it is an array, I can no longer specify
  38. # current_node.children (cause obvs, children isn't a
  39. # method) and cannot move on to the next step.
  40. # How do I escape this array?
  41.  
  42. end # if payload end
  43. # return nil
  44. end # while loop end
  45. end # def breadth end
  46. end # module end
  47.  
  48. class Tree
  49. attr_accessor :payload, :children
  50. include SearchMethods
  51.  
  52. def initialize(payload, children)
  53. @payload = payload
  54. @children = children
  55. end
  56. end
  57.  
  58.  
  59. # The "Leafs" of a tree, elements that have no children
  60. deep_fifth_node = Tree.new(5, [])
  61. eleventh_node = Tree.new(11, [])
  62. fourth_node = Tree.new(4, [])
  63.  
  64. # The "Branches" of the tree
  65. ninth_node = Tree.new(9, [fourth_node])
  66. sixth_node = Tree.new(6, [deep_fifth_node, eleventh_node])
  67. seventh_node = Tree.new(7, [sixth_node])
  68. shallow_fifth_node = Tree.new(5, [ninth_node])
  69.  
  70. # The "Trunk" of the tree
  71. trunk = Tree.new(2, [seventh_node, shallow_fifth_node])
  72.  
  73. p trunk.breadth(5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement