Reputation: 26952
Suppose I want to traverse a grid like in Cantor's proof of the countability of the rationals...
What's a function that takes an integer n and returns the row and column number for the nth cell in that traversal?
Upvotes: 2
Views: 786
Reputation: 26952
First we need the formula for the nth triangular number, as well as the inverse of that function:
t[n_] := n*(n+1)/2
ti[x_] := Floor[(Sqrt[8*x+1]-1)/2]
Then we can define Cantor's ZigZag like so:
zig[n_] := Module[{y = n-1-t[ti[n-1]]},
{ti[n-1]-y, y} + 1]
(I wrote and tested this in Mathematica but it's just arithmetic so will look about the same in any language.)
Upvotes: 1
Reputation: 2286
If you just want a traversal there's no need for a closed form.
You can just use a sequence:
function*(grid){var r=0, c=0
for(;;){yield grid[r][c]; c++; r--; if (r === -1) {r = c; c = 0}}
}
Upvotes: 3