Last active
August 1, 2020 07:49
-
-
Save msg7086/339367f39431e0b6e40cf9e34a2c1d52 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node | |
attr_accessor :parent, :value, :width | |
attr_reader :left, :right | |
def initialize(value, left=nil, right=nil) | |
@value = value | |
@parent = nil | |
self.left = left | |
self.right = right | |
end | |
def left=node | |
@left = node | |
node&.parent = self | |
end | |
def right=node | |
@right = node | |
node&.parent = self | |
end | |
def my_width | |
value.to_s.size | |
end | |
def left_width | |
@left&.width || (my_width / 2) | |
end | |
def right_width | |
@right&.width || (my_width / 2) | |
end | |
def width | |
left_width + right_width + 1 | |
end | |
def draw_me | |
value.to_s.rjust(left_width + my_width / 2 + 1).ljust(width) | |
end | |
def draw_sticks | |
return nil unless @left || @right | |
left_stick = (@left ? '/' : '').rjust(left_width) | |
right_stick = (@right ? '\\' : '').ljust(right_width) | |
left_stick + ' ' + right_stick | |
end | |
def draw | |
pic = [draw_me] | |
sticks = draw_sticks | |
return pic unless sticks | |
pic << sticks | |
left_pic = @left&.draw || [] | |
right_pic = @right&.draw || [] | |
depth = [left_pic.size, right_pic.size].max | |
left_pic.fill(' ' * left_width, left_pic.size...depth) | |
right_pic.fill(' ' * right_width, right_pic.size...depth) | |
pic += left_pic.zip(right_pic).map {|l,r| l + ' ' + r} | |
pic | |
end | |
end | |
l = Node.new 20 | |
l = Node.new 16, l | |
r = Node.new 776655 | |
r = Node.new 13, r | |
l1 = Node.new 7, l, r | |
l = Node.new 17 | |
r = Node.new 24 | |
r1 = Node.new 5, l, r | |
root = Node.new 3, l1, r1 | |
puts root.draw | |
# 3 | |
# / \ | |
# 7 5 | |
# / \ / \ | |
# 16 13 17 24 | |
# / / | |
# 20 776655 | |
l = Node.new 100 | |
r = Node.new 50 | |
10.times do |i| | |
l = Node.new i, l | |
r = Node.new i, nil, r | |
end | |
root = Node.new 123, l, r | |
puts root.draw | |
# 123 | |
# / \ | |
# 9 9 | |
# / \ | |
# 8 8 | |
# / \ | |
# 7 7 | |
# / \ | |
# 6 6 | |
# / \ | |
# 5 5 | |
# / \ | |
# 4 4 | |
# / \ | |
# 3 3 | |
# / \ | |
# 2 2 | |
# / \ | |
# 1 1 | |
# / \ | |
# 0 0 | |
# / \ | |
# 100 50 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment