Created
July 11, 2013 18:30
-
-
Save brutuscat/5977916 to your computer and use it in GitHub Desktop.
PHP Cantor implementation using BCMath extension
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 | |
# Need Composer with PHPUnit | |
require 'vendor/autoload.php'; | |
function cantor($x, $y) | |
{ | |
// ((x + y) * (x + y + 1)) / 2 + y; | |
return bcadd(bcdiv(bcmul(bcadd($x, $y), bcadd(bcadd($x, $y), 1)), 2), $y); | |
} | |
function uncantor($z) | |
{ | |
$pair = []; | |
$t = bcdiv(bcadd(-1, bcsqrt( bcadd(1, bcmul(8, $z)) )), 2); | |
$pair[0] = bcsub(bcdiv(bcmul($t, bcadd($t, 3)), 2), $z); | |
$pair[1] = bcsub($z, bcdiv(bcmul($t, bcadd($t, 1)), 2)); | |
return $pair; | |
} | |
$x = '1234'; | |
$y = '6789'; | |
$z = cantor($x, $y); | |
list($xx, $yy) = uncantor($z); | |
\PHPUnit_Framework_Assert::assertEquals($x, $xx); | |
\PHPUnit_Framework_Assert::assertEquals($y, $yy); | |
echo "$x\n"; | |
echo "$y\n"; | |
echo "$z\n"; | |
echo "$xx\n"; | |
echo "$yy\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More info: http://sachiniscool.blogspot.com/2011/06/cantor-pairing-function-and-reversal.html