0

I want to create a hash function that will receive strings and output the corresponding value in an array that has predefined "proportions". For instance, if my array holds the values:

[0] => "output number 1"
[1] => "output number 2"
[2] => "output number 3"

Then the hash function int H(string) should return only values in the range 0 and 2 for any given string (an input string will always return the same key).

The thing is that i want it to also make judgement by predefined proportions so, for instance 85% of given strings will hash out as 0, 10% as 1 and 5% as 2. If there are functions that can emulate normal distribution that will be even better.

I also want it to be fast as it will run frequently. Can someone point me to the right direction on how to approach this in php? I believe I'm not the first one that asked this but I came short digging on SO for an hour.

EDIT:

What i did until now is built a hash function in c. It does the above hashing without proportions (still not comfortable with php):

int StringFcn (const void *key, size_t arrSize)
{
    char *str = key;
    int totalAsciiVal = 0;

    while(*str)
    {
        totalAsciiVal += *str++;
    }

    return totalAsciiVal % arrSize;
}
4

1 回答 1

0

做这样的事情怎么样:

// Hash the string so you can pretty much guarantee it will have a number in it and it is relatively "random"
$hash = sha1($string);

// Iterate through string and get ASCII values
$chars = str_split($hash);
$num = 0;
foreach ($chars as $char) {
    $num += ord($int);
}

// Get compare modulo 100 of the number
if ($num % 100 < 85) {
    return 0;
}
if ($num % 100 < 95) {
    return 1;
}
return 2;

编辑:

您可以直接使用crc32sha1获得足够大的整数,而不是使用 散列(感谢评论中的@nivrig)。

// Convert string to integer
$num = crc32($string);

// Get compare modulo 100 of the number
if ($num % 100 < 85) {
    return 0;
}
if ($num % 100 < 95) {
    return 1;
}
return 2;
于 2013-02-22T23:49:32.057 回答