Weighted Random Letters

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Weighted Random Letters

Post by onion2k »

I need to generate a random letter, but with the likeliness of a letter being generated approximately the same as the ratio of tiles in Scrabble. So an E is 8 times more likely to occur than an X for example. My solution at the moment is to create an array with 8 'e's, 4 'm's, 1 'x' and so on, then to generate a random number equal to the number of items in the array and extract that letter.

Is there a better way?
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

i did something simlar where random pictures were chosen to be displayed, but some pictures had more weighting, and were more likely to be displayed.

I went down the array route that you described, and it worked pretty well

Code: Select all

// Array of priorities
		// 1/2 chance of selecting an image rated as HI
		// 1/3 chance of selecting an image rated as MED
		// 1/6 chance of selecting an image rated as LOW
		$priority=array( 
		    "HI", 
		    "HI", 
		    "HI", 
		    "MED", 
		    "MED", 
		    "LO" 
		);
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Another way might be to reserve integer ranges: 0-7 for e's, 8-11 for m's, and so on. Set a $max value for the random number generator at the end of all that.
Post Reply