tags:

views:

95

answers:

6

Having a md5 hash like:

md5("test") = "098f6bcd4621d373cade4e832627b4f6"

How can I write a function to return a number between 1 and 9 every time I pass the md5 hash to it? The number must always be the same, i.e. myfunc("098f6bcd4621d373cade4e832627b4f6") should always return the same number. Thanks for your help.

A: 

Return the leftmost digit (in 1..9 of course) in the hash considered as a string.

Or have I missed the point ?

High Performance Mark
+4  A: 

Simplest way: find first number in md5 and return it :) You can do it with easy regexp. Of course remember to have some safe return value if no number was found (but it will happen hardly ever).

Thinker
More specifically, it will happen about 1 in 42 billion times.
Michael Borgwardt
+4  A: 

Return 1 all the time. Meets the spec!

More seriously, what do you need this number to represent?

Paul
Remembers me of http://xkcd.com/221/ ;)
elusive
+1 for fun, reminds me of the getRandom joke returning always 4 :)
GôTô
@elusive: lol, exactly the same joke!
GôTô
Stop this! It's becoming rather silly.
Alin Purcaru
"Now, I've noticed a tendency for this question to get rather silly. Now I do my best to keep things moving along, but I'm not having things getting silly. Those two last comments I did got very silly indeed, and that last one about the hash was even sillier. Now, nobody likes a good laugh more than I do...except perhaps my wife and some of her friends...oh yes and Captain Johnston. Come to think of it most people likes a good laugh more than I do. But that's beside the point. Now, let's have a good clean healthy question." - with apologies to the Monty Python team
Paul
+3  A: 

This is WAY overkill, and the suggestion of returning left-most digit is the best...

function myfunc($md5) {
    $total = 0;
    foreach (str_split($md5) as $char) $total += ord($char);
    return $total % 9 + 1;
}

echo myfunc("098f6bcd4621d373cade4e832627b4f6");

This way you can easily change the range of return values you are interested in by modifying the return statment.

Or, a more compact version:

function myfunc2($md5) {
    return array_sum(array_map("ord", str_split($md5))) % 9 + 1;
}

You could even pass the min and max as args:

function myfunc2($md5, $min = 1, $max = 9) {
    return array_sum(array_map("ord", str_split($md5))) % $max + $min;
}

myfunc2("098f6bcd4621d373cade4e832627b4f6", 10, 20);
sberry2A
+1 for refreshing my mind--I couldn't find the function to convert large integers from one base into another.
Álvaro G. Vicario
@Alvaro Your welcome, I think.
Alin Purcaru
@sberry2A, Thank you very much! I'll use the compact version. Cheers.
Tony
A: 

Here's a solution:

return substr(base_convert($md5, 16, 9), -1) + 1;

This is what you probably want although you did not say it.

Alin Purcaru
+2  A: 

You essentially want a hash function of your hash function. This would be some psedo code:

int hashhash(string hash)
    return (hash[0] % 9) + 1;
jcmcbeth