Skip to content

Instantly share code, notes, and snippets.

@chadbrewbaker
Last active December 11, 2015 05:19
Show Gist options
  • Save chadbrewbaker/4551663 to your computer and use it in GitHub Desktop.
Save chadbrewbaker/4551663 to your computer and use it in GitHub Desktop.
Monolithic playground for trees in Ruby
#Node1 = Struct.new(:next,:value)
#Node2 = Struct.new(:left, :right, :value)
#Node = Struct.new(:parent, :left, :right, :value)
#root = Node.new
#n1 = Node.new(root, nil, nil, 99)
#root.left = n1
#puts root.left.value
#puts root.left.right
#Arbitrary one link structures (Transformations)
#parent = Array.new(100)
parents = [nil, 0,1,0,2,1,0,nil]
def ident(a)
return a
end
def siblings(parent)
sibs = Array.new(parent.size)
grouped_by = (0..(parent.size-1)).group_by { |i| parent[i]}
grouped_by[nil].each{|a| sibs[a]=a}
grouped_by.delete(nil)
puts "cork "+grouped_by.to_a.inspect
grouped_by.to_a.each{ |cycle|
puts "bork "+ cycle.inspect
(0..(cycle.size-1)).each{ |i| sibs[cycle[i]] = sibs[cycle[i+1]] }
}
#indexes which map to a number
#in order write their cycles
return sibs
end
def check(a, b, func)
result = func.call(a)
if result != b
puts "#{a} returned #{result} instead of #{b}, ouch"
exit
end
end
grouped_by = (0..(parents.size-1)).group_by { |i| parents[i]}
puts grouped_by.inspect
puts grouped_by[nil].inspect
grouped_by.delete(nil)
puts grouped_by.values.inspect
puts grouped_by.to_a.inspect
{[nil,nil,nil] => [0,1,2], [nil,0,0] => [0, 2,1]}.each{|a, r| check(a, r, method(:siblings)) }
puts "OK"
##ENFORCE A[i] != A[j] where i != j// Permutations
##ENFORCE A[i] < i, nil means a root // Forests, 1 nil at 0 Tree
#sibling = Array.new(100) #permutation of all sibling cycles, canon is lex min
#child = Array.new(100) #index of a child, canon is lex min
# parent -> [sibling, child]
# [sibling, child] -> parent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment