Skip to content

Instantly share code, notes, and snippets.

@hannesl
Created December 18, 2013 23:02
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hannesl/8031402 to your computer and use it in GitHub Desktop.
Save hannesl/8031402 to your computer and use it in GitHub Desktop.
Cantor pairing functions in PHP. Pass any two positive integers and get a unique integer back. Feed the unique integer back into the reverse function and get the original integers back. Explanation and JS implementation here: http://stevegardner.net/2012/07/09/javascript-cantor-pairing-function-and-reverse-function/
<?php
/**
* Calculate a unique integer based on two integers (cantor pairing).
*/
function cantor_pair_calculate($x, $y) {
return (($x + $y) * ($x + $y + 1)) / 2 + $y;
}
/**
* Return the source integers from a cantor pair integer.
*/
function cantor_pair_reverse($z) {
$t = floor((-1 + sqrt(1 + 8 * $z))/2);
$x = $t * ($t + 3) / 2 - $z;
$y = $z - $t * ($t + 1) / 2;
return array($x, $y);
}
@florinutz
Copy link

thanks! :D

@majidamiri
Copy link

NICE THX

@BruceLampson
Copy link

SWEET

@ronaldgreeff
Copy link

Uh, should it not be ((x+y)*(x+y+1)+y)*0.5 ?

@Furgas
Copy link

Furgas commented May 4, 2021

Uh, should it not be ((x+y)*(x+y+1)+y)*0.5 ?

Not according to Wikipedia.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment