我的网站使用来自单个域的各种资源,例如:
http://static.example.com/javascript/common.js
http://static.example.com/javascript/common.css
http://static.example.com/javascript/menu/menu.js
http://static.example.com/javascript/menu/menu.css
http://static.example.com/images/1804/logo/02000100.jpg
http://static.example.com/images/1804/headers/main/09400060.png
http://static.example.com/images/1804/headers/home/1101/06900200-01.jpg
http://static.example.com/images/1804/headers/home/1101/06900200-02.jpg
我需要一个非常简单的字符串哈希函数,将这些 URL 映射到数字,数字为 0、1、2 和 3。该算法应该是确定性和统一的。我已经标记了问题 PHP,但可以接受通用答案。
您可能已经猜到我为什么需要这个;我打算将 URL 更改为,例如:
http://0.static.example.com/javascript/common.js
http://2.static.example.com/javascript/common.css
最佳答案
我更喜欢对字符串进行 crc32
哈希处理,然后将其与极限值取模。
代码:
function numeric_hash($str, $range) {
return sprintf("%u", crc32($str)) % $range;
}
用法:
$str = "http://static.example.com/javascript/common.js
http://static.example.com/javascript/common.css
http://static.example.com/javascript/menu/menu.js
http://static.example.com/javascript/menu/menu.css
http://static.example.com/images/1804/logo/02000100.jpg
http://static.example.com/images/1804/headers/main/09400060.png
http://static.example.com/images/1804/headers/home/1101/06900200-01.jpg
http://static.example.com/images/1804/headers/home/1101/06900200-02.jpg";
$urls = explode("\n", $str);
foreach($urls as $url) {
echo numeric_hash($url, 4) . "\n";
}
输出:
1
3
3
3
1
3
1
3
关于php - 将可变长度 URL 映射到数字 (0...3) 的简单哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13414612/