Skip to content

Instantly share code, notes, and snippets.

@bradediger
Created February 8, 2009 23:09
Show Gist options
  • Save bradediger/60554 to your computer and use it in GitHub Desktop.
Save bradediger/60554 to your computer and use it in GitHub Desktop.
# Cantor-numbering: maps Integer onto (Integer,Integer)
def cantor(z)
w = ((Math.sqrt(8*z+1)-1) / 2).floor
t = ((w**2 + w) / 2).floor
y = z-t
x = w-y
[x,y]
end
# Iterates over the Cartesian product xs*ys in Cantor order
def each_pair(xs,ys)
i = 0
nxs, nys = xs.length, ys.length
loop do
xi, yi = cantor(i)
i+=1
break if xi >= nxs && yi >= nys
next if xi >= nxs || yi >= nys
yield(xs[xi], ys[yi])
end
end
# >> each_pair([1,2,3,4],[9,8,7]){|x, y| puts "x=#{x}, y=#{y}"}
# x=1, y=9
# x=2, y=9
# x=1, y=8
# x=3, y=9
# x=2, y=8
# x=1, y=7
# x=4, y=9
# x=3, y=8
# x=2, y=7
# x=4, y=8
# x=3, y=7
# x=4, y=7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment