Created
November 4, 2014 14:58
-
-
Save AndreBaumeier/63a5077c0ce4f1185537 to your computer and use it in GitHub Desktop.
short url generator
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 ShortUrlGenerator { | |
/** | |
* From http://rosettacode.org/wiki/Linear_congruential_generator#PHP | |
*/ | |
public static function bsd_rand($seed) { | |
return function() use (&$seed) { | |
return $seed = (1103515245 * $seed + 12345) % (1 << 31); | |
}; | |
} | |
/** | |
* From http://stackoverflow.com/questions/14556104/generating-a-unique-and-random-6-character-long-string-to-represent-link-in-ruby | |
*/ | |
public static function encode_alphas($n, $alphas) { | |
$result = ''; | |
for ($i=0;$i<6;$i++) { | |
$m = $n % count($alphas); | |
$n = $n / count($alphas); | |
$result .= $alphas[$m]; | |
} | |
return $result; | |
} | |
public static function generateUrl($id) { | |
$lcg = self::bsd_rand($id); | |
return self::encode_alphas($lcg(), range('a', 'z')); | |
} | |
} | |
print ShortUrlGenerator::generateUrl(10000001); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment