Created
February 8, 2009 23:09
-
-
Save bradediger/60554 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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