I got this piece of code from a google search of weighted random...but i just cant help but shake the feeling that it is insanely innefficent. Can anyone take a quick look over it and tell me if it will add more load to the already overloaded server 2
| Code: |
| $weights= array(
"1" => 10000000, //Dustin "2" => 9800000, //Carl "3" => 11000000, //Pat "4" => 1 //Pat's Mom ); function weightRandom($weights){ /*******************************\ | Copyright 2006 Erik Eloff | | This code is free to use only | | if you leave this notice here | \*******************************/ $loop; $topNum; $randNum; foreach( $weights as $val ){ $topNum += $val; } $randNum = rand()%$topNum+1; $topNum = 0; foreach( $weights as $key => $val ){ $topNum += $val; if( $val > 0 ){ if( $topNum >= $randNum ){ return $key; } } } } |
