Last active
March 27, 2016 23:25
-
-
Save kevinkl3/14b1ba9465cb13d13d00 to your computer and use it in GitHub Desktop.
PHP implementation based on this SO answer: http://stackoverflow.com/a/742047/3393666
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 | |
class UrlShortener{ | |
private static $alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; | |
public static function encode($i){ | |
$alphabet = static::$alphabet; | |
$base = strlen($alphabet); | |
$result = ""; | |
do{ | |
$result = $alphabet[ $i % $base] . $result; | |
//$i = intdiv($i, $base); //intdiv requires PHP >= 7 | |
$i = ($i - ($i % $base)) / $base; | |
}while($i > 0); | |
return $result; | |
} | |
public static function decode($s){ | |
$alphabet = static::$alphabet; | |
$base = strlen($alphabet); | |
$id = 0; | |
$li = strlen($s)-1; | |
$chars = str_split($s); | |
foreach($chars as $c){ | |
$v = strpos($alphabet,$c); | |
$id += $v * pow($base,$li--); | |
} | |
return $id; | |
} | |
public static function test(){ | |
for($i = 0; $i < 100000; $i++){ | |
$encoded = static::encode($i); | |
$decoded = static::decode($encoded); | |
if( $i != $decoded){ | |
echo "Error, $decoded != $i \n"; | |
exit(1); | |
}else{ | |
echo "Good, $i ($encoded) == $decoded\n"; | |
} | |
} | |
} | |
} | |
UrlShortener::test(); | |
//To test on command line: | |
//php UrlShortener.php | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment