PDA

View Full Version : A hash of arbitrary range or determinative randomizer?


Banana
2008-06-05, 22:23
I'm pretty sure this exists in some form, but may not know the right keyword to google it effectively.

I'm looking for information on how to implement something that creates more or less determinative result based on an input data to semi-randomly select something else.

Pseudo code:
public int(string foo)
{
int bar; int iter;
bar = foo.toInt();
iter = rand(bar, 0, 7); ///Selects a number between 0 to 7 based on the value of bar
return iter;
}

The idea is that the rand function, like any hash functions, would always produce the same result for same input but give different result for different result with no discernible pattern between a set of inputs to set of outputs. Therefore, the standard rand() won't do it for me.

Does such function exists? Any pointers will be much appreciated.

Kickaha
2008-06-05, 22:26
http://en.wikipedia.org/wiki/Perfect_hash_function

http://www.partow.net/programming/hashfunctions/

Banana
2008-06-06, 09:42
See? I'd never have thought of "perfect hash" as a keyword! :p

Anyway, looking over at the sample codes, it looks that generally, a string and a length is all that is needed to be passed. Some may ask for number of keys or a random seed. However, this gives me no control over the output which must fall within a range I specify. I am not concerned about collisions or stuff like that; I just want to randomly select a number within a range I give, and get same results every time I run the same input.

Or am I missing something?

Kickaha
2008-06-06, 10:01
No. :)

Just hash the string down to an integer, and use some sequence of the bits (lowest n, highest n, low bit from first n digits...) to select into an array of length k that you're prefilled with calls to rand().

The hashing guarantees a particular integer, the bit selection grabs the correct bucket.

Banana
2008-06-06, 10:06
Gotcha. Many thanks!

*goes back into the innards of the code*