Skip to content

Instantly share code, notes, and snippets.

@acrookston
Last active April 29, 2017 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acrookston/03b2519f4124531a6bcb18479a9a9201 to your computer and use it in GitHub Desktop.
Save acrookston/03b2519f4124531a6bcb18479a9a9201 to your computer and use it in GitHub Desktop.
Tree sorting in ruby
# Question: https://www.dropbox.com/s/4dlhs6x69cmj8uv/Screenshot%202017-04-29%2012.21.05.png?dl=0
# Time limit: 30min
# Finished in 28min
# It should be possible to load the tree in one pass. I just didn't have time to rewrite that part.
require "rubygems"
require "json"
locations = JSON.parse(STDIN.read)
class Node
# Confusing use of node.node... :)
attr_accessor :node, :children
def initialize(node)
@node = node
@children = []
end
def to_s(level=nil)
str = level == nil ? "" : "#{"-" * level}#{@node["name"]}\n"
level = level == nil ? 0 : level + 1
return str + children.sort{|a,b| a.node["name"] <=> b.node["name"] }.map {|c| c.to_s(level) }.join("")
end
def append(value)
children << Node.new(value)
end
def find(id)
return self if @node["id"] == id
for child in children
node = child.find(id)
return node if node != nil
end
nil
end
end
def sort(list, into)
unsorted = []
list.each do |location|
node = into.find(location["parent_id"])
if node != nil
node.append(location)
else
unsorted << location
end
end
unsorted
end
STDERR.puts locations.inspect
root = Node.new({id: nil}) # makes the top-level nodes match on nil
unsorted = locations
while unsorted.count > 0
unsorted = sort(unsorted, root)
end
puts root.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment