如何平滑随机分布?

时间:2013-04-18 22:45:58

标签: algorithm math random distribution random-sample

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

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

示例: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的人。

我怎样才能解决这个问题呢?

1 个答案:

答案 0 :(得分:4)

如果您使用真正的哈希函数而不是仅仅汇总ASCII / Unicode代码点,那么您可能会有更好的运气。 The djb2 function非常适合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;

另见What's a good hash function for English words?