Advertisement
Guest User

Untitled

a guest
Apr 29th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. # frozen_string_literal: true
  2.  
  3. class Tree
  4. attr_reader :data, :children
  5.  
  6. def initialize(data, children)
  7. @data = data
  8. @children = children
  9. end
  10. end
  11.  
  12. # The "Leafs" of a tree, elements that have no children
  13. deep_fifth_node = Tree.new(5, [])
  14. eleventh_node = Tree.new(11, [])
  15. fourth_node = Tree.new(4, [])
  16.  
  17. # The "Branches" of the tree
  18. ninth_node = Tree.new(9, [fourth_node])
  19. sixth_node = Tree.new(6, [deep_fifth_node, eleventh_node])
  20. seventh_node = Tree.new(7, [sixth_node])
  21. shallow_fifth_node = Tree.new(5, [ninth_node])
  22.  
  23. # The "Trunk" of the tree
  24. trunk = Tree.new(2, [seventh_node, shallow_fifth_node])
  25.  
  26.  
  27.  
  28. # What we expect to see:
  29. # 2 -> 7 -> 6 -> 5
  30. # 11
  31. # 5 -> 9 -> 4
  32. def depth_first_search(node, target, unvisited=[])
  33. return node if node.data == target
  34. print("#{node.data} -> ") # print debugging output
  35. return if node.children.empty? && unvisited.empty?
  36.  
  37. if node.children.count == 0
  38. puts # newline in output
  39. child = unvisited.pop
  40. depth_first_search(child, target, unvisited)
  41. elsif node.children.count == 1
  42. child = node.children.first
  43. depth_first_search(child, target, unvisited)
  44. elsif node.children.count > 1
  45. child = node.children.first
  46. unvisited.push(*node.children[1..-1])
  47. depth_first_search(child, target, unvisited)
  48. end
  49. end
  50.  
  51. depth_first_search(trunk, 22) # => nil
  52. # >> 2 -> 7 -> 6 -> 5 ->
  53. # >> 11 ->
  54. # >> 5 -> 9 -> 4 ->
  55.  
  56. depth_first_search(trunk, 9) # => #<Tree:0x007fbe340788d0 @data=9, ...>
  57. # >> 2 -> 7 -> 6 -> 5 ->
  58. # >> 11 ->
  59. # >> 5 ->
  60.  
  61.  
  62.  
  63. # What we expect to see:
  64. # 2 ->
  65. # 7 -> 5
  66. # 6 -> 9
  67. # 5 -> 11 -> 4
  68. def bfs(nodes, target)
  69. search_list = Array(nodes)
  70. return if search_list.empty?
  71. next_search_list = []
  72.  
  73. search_list.each do |node|
  74. print("#{node.data} -> ")
  75. return node if node.data == target
  76. next_search_list.push(*node.children)
  77. end
  78.  
  79. puts # for debugging output
  80. bfs(next_search_list, target)
  81. end
  82.  
  83. bfs(trunk, 999) # => nil
  84. # >> 2 ->
  85. # >> 7 -> 5 ->
  86. # >> 6 -> 9 ->
  87. # >> 5 -> 11 -> 4 ->
  88.  
  89. bfs(trunk, 9) # => #<Tree:0x007f9aef84d438 @data=9, ...>
  90. # >> 2 ->
  91. # >> 7 -> 5 ->
  92. # >> 6 -> 9 ->
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement