Convert infinite 2D plane integer coords to 1D number

You need the Cantor pairing function, tuned up to accept integers instead of naturals. The basic function takes a pair of naturals (including zero) $x,y$ and returns a natural $\pi(x,y)=\frac 12(x+y)(x+y+1)+y$. It is invertible, so given $\pi(x,y)$ you can recover $x$ and $y$. Now just take your integers to naturals by $$f(z)=\begin {cases} 2z&z\ge 0\\-2z-1& z \lt 0\end {cases}$$ pair them and you have your result.

You can do your idea with the Ulam spiral: enter image description here The cell numbered $1$ is the origin. Note the odd squares follow the downward right diagonal and the even squares start just above $1$ and follow an upward left diagonal. If we are given a coordinate $(x,y)$ we first find the direction the side is going. If $x \gt 0, x \gt |y|$, the cell is on an upward side. The corner at the bottom is $(x,-x)$ and has number $(2x-1)^2$ The number in our cell is $y+x$ cells above, so the number is $(2x-1)^2+y+x$. You can go through the other three sides similarly. To go the other direction, given a cell number find the perfect square below it. Find the location of the square on the diagonal, then count the number of squares from there as needed.


Other answers state how to convert integers to naturals, I won't repeat this step. Let's suppose you have two naturals, e.g.:

$$ 123 $$ $$ 98765 $$

Add leading zeros to obtain equal number of digits:

$$ 00123 $$ $$ 98765 $$

And "interleave":

$$ 0908172635 $$

Reverting is trivial: you pick digits from either odd or even positions.

Notes:

  • the representation depends on the base of the numeral system you use;
  • you can expand the method to non-negative reals in a quite obvious way;
  • similarly you can create a method that takes any fixed number of numbers and yields one number.

There are also tools from number theory. We can first map all integers to non-negative ones, which is easy, just take $$f(n)=\left\{\begin{align}&2n&n\ge0\\&-2n-1&n<0\end{align}\right.$$ as Ross pointed out. Now us take the pair $(m,n)$ to be $2^{f(m)}3^{f(n)}$. Since we can uniquely decompose positive integers into prime factors, this function is invertible, and you have your result.

Tags:

Geometry