Created
December 18, 2013 23:02
-
-
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/
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
<?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); | |
} |
NICE THX
SWEET
Uh, should it not be ((x+y)*(x+y+1)+y)*0.5 ?
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
thanks! :D