我正在尝试计算一个单词的“分数”,以便它将用于确定它在 Redis 排序集中的字典顺序(按字母顺序列出的单词)。
阅读 this post它说:
How to turn a word into a score?
For instance, if you want to use the first four letters to produce the score, this is the rule:
score = first-byte-value*(256^3) + second-byte-value*(256^2) + third-byte-value*(256^1) + fourth-byte-value
Just omit from the sum non existing chars if the word is < 4 chars in length.
Why this works? You are just considering the bytes as digits of a radis-256 number :)
根据这个理论,我想出了以下代码来测试它是否适用于 PHP 数组:
$words = array('abcd', 'hello', 'dogs', 'hiya');
$newWords = array();
foreach ($words as $word) {
$len = strlen($word);
if ($len > 4) {
$len = 4;
}
$i = 0;
$j = $len - 1;
$score = 0;
while ($i < $len) {
$byte = ord($word[$i]);
if ($j == 0) {
$score += $byte;
}
else {
$score += $byte * (256 ^ $j);
}
$i++;
$j--;
}
$newWords[$score] = $word;
}
ksort($newWords);
print_r($newWords);
但是这会返回:
Array
(
[75950] => abcd
[80858] => hello
[81124] => dogs
[85220] => hiya
)
这不是按字母顺序排列的。
谁能发现问题(显然分数计算有误)?我可能误解了帖子:-/
最佳答案
我稍微改进了代码并改为使用 pow
$words = array('abcd', 'hello', 'dogs', 'hiya');
$newWords = array();
foreach ($words as $word) {
$len = strlen($word);
if ($len > 4) {
$len = 4;
}
$i = 0;
$j = $len - 1;
$score = 0;
while ($i < $len) {
$byte = ord($word[$i]);
$score += $byte * pow(256, $j);
$i++;
$j--;
}
$newWords[$score] = $word;
}
ksort($newWords);
print_r($newWords);
它完全符合您的预期:
Array ( [1633837924] => abcd [1685022579] => dogs [1751477356] => hello [1751742817] => hiya )
你实际上使用了 XOR http://www.php.net/manual/en/language.operators.bitwise.php
关于php - 将单词转换为字典顺序的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13364680/