Skip to content

Instantly share code, notes, and snippets.

@trishume
Created July 18, 2011 23:27
Show Gist options
  • Save trishume/1090946 to your computer and use it in GitHub Desktop.
Save trishume/1090946 to your computer and use it in GitHub Desktop.
Graphviz collatz.
# gem install GraphvizR
require 'graphviz_r'
# small recursive version
def collatzr(num,arr = [])
return arr if arr.unshift(num)[0] == 1
num.even? ? collatzr(num / 2,arr) : collatzr(num * 3 + 1,arr)
end
# pretty looping version
def collatz(num,arr = [])
while num != 1
arr << num
num = num.even? ? num / 2 : num * 3 + 1
end
arr.push(1)
end
#graphing versions
#each version takes only 9 lines!
def coll_max_l(depth = 100, parent = nil,num = 1)
num1 = (num-1)/3.0
coll_max_l(depth,num,num1.to_i)[:label => "3n+1"] if depth > num1 && num1.floor == num1 && num1 > 0 && num1.floor.odd? && num != 4
coll_max_l(depth,num,num*2)[:label => "n/2"] if depth > num*2 && (num*2).even?
$g[num.to_s] >> $g[parent.to_s] if parent
end
def coll_max(depth = 100, parent = nil,num = 1)
num1 = (num-1)/3.0
coll_max(depth,num,num1.to_i) if depth > num1 && num1.floor == num1 && num1 > 0 && num1.floor.odd? && num != 4
coll_max(depth,num,num*2) if depth > num*2 && (num*2).even?
$g[num.to_s] >> $g[parent.to_s] if parent
end
def coll_depth(depth = 100, parent = nil,num = 1)
num1 = (num-1)/3.0
coll_depth(depth-1,num,num1.to_i) if depth > 0 && num1.floor == num1 && num1 > 0 && num1.floor.odd? && num != 4
coll_depth(depth-1,num,num*2) if depth > 0 && (num*2).even?
$g[num.to_s] >> $g[parent.to_s] if parent
end
def coll_depth_l(depth = 100, parent = nil,num = 1)
num1 = (num-1)/3.0
coll_depth_l(depth-1,num,num1.to_i)[:label => "3n+1"] if depth > 0 && num1.floor == num1 && num1 > 0 && num1.floor.odd? && num != 4
coll_depth_l(depth-1,num,num*2)[:label => "n/2"] if depth > 0 && (num*2).even?
$g[num.to_s] >> $g[parent.to_s] if parent
end
# non-labeled, to max
$g = GraphvizR.new 'collatz_max'
coll_max(300)
$g.output
# labeled, to max
$g = GraphvizR.new 'collatz_max_l'
coll_max_l(50)
$g.output
# non-labeled, to depth
$g = GraphvizR.new 'collatz_depth'
coll_depth(15)
$g.output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment