Author Topic: Weighted Random Select  (Read 780 times)

Offline genmac

  • Level 7
  • *
  • Posts: 34
  • Reputation: +0/-0
    • View Profile
    • Castle Siege
Weighted Random Select
« on: January 07, 2009, 04:37:29 PM »
I've seen a lot of google results for this problem (a weighted random select from mysql) that claim to give you a result, but do not actually work.  This is the solution I use:

Code: [Select]
select * from random_table order by -LOG(1.0-RAND())/weight limit 1

Obviously you need a field named weight, I use 5 (rarest), 10 (uncommon), 20 (common).  Since I use this for procedural generation, and not at "runtime" where the player would be hitting the query a lot, I'm not overly concerned about performance.

Relevant links:
http://www.kahunaburger.com/2008/10/13/selecting-random-weighted-records-from-mysql/
http://use.perl.org/~bart/journal/33630
« Last Edit: January 07, 2009, 05:48:52 PM by genmac »
Castle Siege - persistent browser based medieval warfare

 


SimplePortal 2.3.3 © 2008-2010, SimplePortal