Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- cat nodes
- #!/usr/bin/env ruby
- module Chain
- class Node
- attr_accessor :left, :right, :node_count, :name
- def initialize(name)
- @name = name
- @node_count = 0
- end
- def has_left?
- !left.nil?
- end
- def has_right?
- !right.nil?
- end
- def send_left(data)
- if has_left?
- left.from_right(data)
- elsif has_right?
- # found the left boundary, bounce right with the final count.
- send_right(node_count: data[:counter])
- @node_count = data[:counter]
- end
- end
- def send_right(data)
- if has_right?
- right.from_left(data)
- elsif has_left?
- # found right boundary, bounce left with the counter.
- left.from_right(counter: 1) if data[:counter]
- end
- end
- def from_left(data)
- @node_count = data[:node_count] if data[:node_count]
- send_right(data)
- end
- def from_right(data)
- data[:counter] += 1 if data[:counter]
- send_left(data)
- end
- end
- class List
- attr_accessor :nodes
- end
- end
- # Setup
- node_x = Chain::Node.new("node_x")
- node_y = Chain::Node.new("node_y")
- node_z = Chain::Node.new("node_z")
- node_a = Chain::Node.new("node_a")
- node_x.right = node_y
- node_y.left = node_x
- node_y.right = node_z
- node_z.left = node_y
- node_z.right = node_a
- node_a.left = node_z
- list = Chain::List.new
- list.nodes = [node_x, node_y, node_z, node_a].shuffle
- puts "node counts before"
- list.nodes.each { |node| puts "Node: #{node.name} Count: #{node.node_count}" }
- list.nodes.each { |node| node.send_right(counter: 0) }
- puts "node counts after"
- list.nodes.each { |node| puts "Node: #{node.name} Count: #{node.node_count}" }
- # Setup
- node_a = Chain::Node.new("node_a")
- node_b = Chain::Node.new("node_b")
- node_c = Chain::Node.new("node_c")
- node_d = Chain::Node.new("node_d")
- node_e = Chain::Node.new("node_e")
- node_f = Chain::Node.new("node_f")
- node_g = Chain::Node.new("node_g")
- node_a.right = node_b
- node_b.left = node_a
- node_b.right = node_c
- node_c.left = node_b
- node_c.right = node_d
- node_d.left = node_c
- node_d.right = node_e
- node_e.left = node_d
- node_e.right = node_f
- node_f.left = node_e
- node_f.right = node_g
- node_g.left = node_f
- list = Chain::List.new
- list.nodes = [node_a, node_b, node_c, node_d, node_e, node_f, node_g].shuffle
- puts "node counts before"
- list.nodes.each { |node| puts "Node: #{node.name} Count: #{node.node_count}" }
- list.nodes.each { |node| node.send_right(counter: 0) }
- puts "node counts after"
- list.nodes.each { |node| puts "Node: #{node.name} Count: #{node.node_count}" }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement