<?php
define('ALPHABET', 'acdegilmnoprstuw');
$hash = 680131659347;
$string = 'leepadg';
echo sprintf('Hash of string «%s» is «%s».', $string, get_hash(ALPHABET, $string)), PHP_EOL
, sprintf('String of hash «%s» is «%s».', $hash, unhash(ALPHABET, $hash))
;
function get_hash($alphabet, $string) {
$h = 7;
$len = strlen($string);
for($i = 0; $i < $len; $i++) {
$h = ($h * 37 + strpos($alphabet, $string[$i]));
}
return $h;
}
function unhash($alphabet, $hash) {
$result = '';
$len = strlen($alphabet);
while ($hash > 7) {
for ($i = 0; $i < $len; $i++) {
$newres = ($hash - $i) / 37;
if (is_int($newres)) {
$result .= $alphabet[$i];
$hash = $newres;
break;
}
}
echo $result;
return strrev($result);
}
}
preferences:
35.87 ms | 402 KiB | 5 Q