Advertisement
Guest User

Untitled

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