New problems, new algorithms

I couldn't help but blog this. On the [C# lang] list the following question was asked:

I want to generate a random number within a specified range.

Say there are a bunch of players on my basketball team who usually sit on the bench. Each player is ranked, e.g.

John 5
Bill 1
Derek 10

etc.

The higher the rank, the more chances this player will be chosen to to play.

 

To which Eddie Garmon replied:

instead of using an array that has each item added for the # of increaded(sic) possibilities, do a little simple math instead.

sum up the total possible outcomes(sum of all players weight) use this as your rand max, and get your random # randomize your player array.

walk the array subtracting the weight of each player from your random # when your random # is less than 0, use that player.

 

I liked that :-)

3 Comments

  • I'm not 100% certain of this (statistics is about 20 years in my past), but I believe that you don't need to randomize the player array to have this (quite slick) algorithm work. Assuming that the distribution of random numbers is uniform across the entire range, the order of the players in the array is inconsequential. Using your example, Bill will have a 1 in 16 chance of being selected regardless of where Bill is in the player array.


  • Darren,



    Do you mind posting some code of the solution. I am having a hard time understanding the solution.



    Thanking you for your time,



    -ron


  • Hi,



    You have a cool blog.Lot's of info.

Comments have been disabled for this content.