We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › algo for strings -> widely dist. int vals
Page Index Toggle Pages: 1
algo for strings -> widely dist. int vals? (Read 431 times)
algo for strings -> widely dist. int vals?
Dec 4th, 2008, 9:38pm
 
So this isn't processing specific, but...
I'm thinking about making one of those "name generators" that will input a name and output a royalty title, and I'd like to ensure that A. the same name always returns the same title and B. there's a fairly good distribution across all the titles

So I was thinking that I should take each character, maybe convert into an int via a char, doing some kind of math to make the number a bit larger, and then doing mod arithmetic to  get an array offset. Again, the result for a typical 4 or 5 character name should be much larger than the # of titles (not sure how many... maybe a couple hundred)

Actually in typing this I thought of a possible solution... basically treat a name like a base-26 number, and then mod it by the number of names. Would that work?
Re: algo for strings -> widely dist. int vals?
Reply #1 - Dec 4th, 2008, 10:40pm
 
a hashing function is likely what you want, and String happens to have one, google for "java String.hashCode()"
Re: algo for strings -> widely dist. int vals?
Reply #2 - Dec 5th, 2008, 10:51am
 
I am not sure what you mean by "royalty title". As in "monarchy" (Probably not as in copyright, as I first thought...) Can you give some examples

And indeed, hashing can be the solution, although finding a good hashing algorithm is a difficult art.
Re: algo for strings -> widely dist. int vals?
Reply #3 - Dec 5th, 2008, 5:48pm
 
Yeah, Wikipedia has a page like http://en.wikipedia.org/wiki/List_of_monarchs_by_nickname (not quite the one I was thinking of)

Actually, I ended up doing it in PHP, and md5 is the trick, since you want consistent results for the same string...


$options = array("the brave","the dumb","the younger");
print  $options[abs(intval(hexdec(substr(md5($text),0,8)))) % sizeof($options)];

(the abs(intval()) stuff has to do with PHP treating things as negative...)
Page Index Toggle Pages: 1