3

我正在尝试随机化游戏中角色的外观,但使用他们的名字作为种子。因此,如果您在游戏中遇到“鲍勃”,他将始终拥有相同的头发/眼睛等。

现在我只是从他们的名字中生成一个数字(通过添加所有的字符代码),然后使用模数来决定他们有什么选项。

示例:Bob 的种子是 276 (66 + 111 + 98)。276% 的发型数量(40 种)导致 36 种。

这很好,但对于 350 多个名称的列表,分布如下所示:

hair style: 0 / # of people using it: 15
hair style: 1 / # of people using it: 8
hair style: 2 / # of people using it: 4
hair style: 3 / # of people using it: 5
hair style: 4 / # of people using it: 7
hair style: 5 / # of people using it: 5
hair style: 6 / # of people using it: 7
hair style: 7 / # of people using it: 14
hair style: 8 / # of people using it: 12
hair style: 9 / # of people using it: 6
hair style: 10 / # of people using it: 7
hair style: 11 / # of people using it: 2
hair style: 12 / # of people using it: 7
hair style: 13 / # of people using it: 10
hair style: 14 / # of people using it: 11
hair style: 15 / # of people using it: 7
hair style: 16 / # of people using it: 12
hair style: 17 / # of people using it: 7
hair style: 18 / # of people using it: 6
hair style: 19 / # of people using it: 10
hair style: 20 / # of people using it: 5
hair style: 21 / # of people using it: 10
hair style: 22 / # of people using it: 11
hair style: 23 / # of people using it: 3
hair style: 24 / # of people using it: 6
hair style: 25 / # of people using it: 8
hair style: 26 / # of people using it: 5
hair style: 27 / # of people using it: 11
hair style: 28 / # of people using it: 10
hair style: 29 / # of people using it: 6
hair style: 30 / # of people using it: 13
hair style: 31 / # of people using it: 11
hair style: 32 / # of people using it: 10
hair style: 33 / # of people using it: 12
hair style: 34 / # of people using it: 3
hair style: 35 / # of people using it: 11
hair style: 36 / # of people using it: 9
hair style: 37 / # of people using it: 4
hair style: 38 / # of people using it: 10
hair style: 39 / # of people using it: 15

分布不是很顺利,到处都是(不足为奇)。我会遇到很多发型 #0 的人,而几乎没有发型 #11 的人。

我怎样才能把它弄平一点?

4

1 回答 1

4

如果您使用真正的散列函数而不是仅仅对 ASCII/Unicode 代码点求和,您可能会有更好的运气。 djb2函数对于 ASCII 输入非常流行:

unsigned long hash(unsigned char *str) {
    unsigned long hash = 5381;
    int c;

    while (c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;
}

所以,例如,

unsigned long hairStyle = hash(characterName) % kHairStyleCount;

另请参阅什么是英语单词的好散列函数?

于 2013-04-18T22:56:42.253 回答