【问题标题】:Simple hashing function to map variable length URLs to numbers (0...3)将可变长度 URL 映射到数字的简单散列函数 (0...3)
【发布时间】:2012-11-05 01:28:49
【问题描述】:

我的网站使用来自单个域的各种资源,例如:

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

【问题讨论】:

  • 我要说strlen($str) % $num ...它肯定很快:)
  • 是快速但不统一...查看包含单词 headers 的 url?我将在一个页面上有大约 15 个,因此 20 个 URL 中有 15 个将具有哈希 = 3。
  • 是的,这无疑更适用于更像人类的图像名称:)

标签: php algorithm hash


【解决方案1】:

我更喜欢对字符串进行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

【讨论】:

  • hexdec 是怎么回事?我用你的示例代码得到负数,顺便说一句,这不是问题。
  • @SalmanA,哎呀,我以为crc32 返回一个十六进制值。您必须使用 32 位 php,其中函数可以根据 manual 返回负整数。我敢肯定,用abs() 包装它也会给你一个正态分布。
【解决方案2】:

如果你有很多 URL,你应该只是一个强哈希,然后使用 mod <noBuckets>

MD5(URL) % 4

如果您的网址很少,或者您的大小或调用频率不均匀,则“随机”分布可能会很糟糕,您应该只创建四个列表,然后将您的网址静态分配给每个列表,手动或使用基于数量的启发式算法每个 URL 的请求数。

【讨论】:

    猜你喜欢
    • 2013-07-09
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多