Skip to content

Instantly share code, notes, and snippets.

@nhocki
Created November 10, 2016 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nhocki/42d3dda920a4ce641af83dbd683a3c1a to your computer and use it in GitHub Desktop.
Save nhocki/42d3dda920a4ce641af83dbd683a3c1a to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'pry'
$nodes = Hash.new
class Index
attr_reader :children, :name
attr_accessor :parent
def initialize(size, name, children = Array.new)
@size = size
@name = name
@children = children
@type = :leaf
end
def full?
@children.size == @size
end
def add_sitemap(node)
@type = :leaf
@children << node
end
def add_index(node)
@type = :node
node.parent = name
@children << node
end
def to_s
"<< Node #{name} (#{@type}) >>"
end
end
def build_tree_from_array(size, arr)
num = 1
indeces = Array.new
while arr.any? do
index = Index.new(size, "Index #{num}")
num += 1
$nodes[index.name] = index
while arr.any? && !index.full? do
node = arr.shift
puts "Processing #{node} into #{index}"
index.add_sitemap(node)
end
indeces << index
end
while indeces.any? do
index = Index.new(size, "Index #{num}")
num += 1
$nodes[index.name] = index
while indeces.any? && !index.full? do
node = indeces.shift
puts "Processing #{node} into #{index}"
index.add_index(node)
end
if indeces.any? && index.full?
indeces.push(index)
else
return index
end
end
end
a = build_tree_from_array(3, (1..100).to_a)
binding.pry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment