Skip to content

Instantly share code, notes, and snippets.

@jtbandes
Created March 22, 2012 01:27
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 jtbandes/2155018 to your computer and use it in GitHub Desktop.
Save jtbandes/2155018 to your computer and use it in GitHub Desktop.
Recursively generated graphs
# A nifty class providing recursive graph generation
class Graph
def initialize(*args, &blk)
@edges = []
@block = blk
@nodes = 0
@inited = false
yield self, *args if block_given?
end
def init
return if @inited
@inited = true
yield self
end
def recurse(*args)
@block[self, *args] unless @block.nil?
end
def edge(a, b); @edges << [a, b]; end
def nodes(n); @nodes = n; end
def next_node!; @nodes += 1; end
def to_s; @edges.map {|e| e * " "} * "\n"; end
end
# Example:
g = Graph.new(ARGV[0].to_i, 1, 2, 3) do |g, n, a, b, c|
# Initial configuration: a triangle of 3 nodes
g.init do
g.nodes 3
g.edge(1, 2)
g.edge(2, 3)
g.edge(3, 1)
end
# A recursively-generated structure
if n > 0
new_id = g.next_node!
g.edge(a, new_id)
g.edge(b, new_id)
g.edge(c, new_id)
g.recurse(n-1, a, b, new_id)
g.recurse(n-1, a, new_id, c)
g.recurse(n-1, new_id, b, c)
end
end
puts g
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment