PHP full probability calculation functions (optimized version) are essential for Webgame development. For more information, see.
The Code is as follows:
$ Setting = array (
// Black Probability
0 => 0.99,
// White Probability
1 => 0.01,
);
// Requires the GD Library
Header ("Content-type: image/png ");
$ Im = imagecreatetruecolor (256,256) or die ("Cannot Initialize new GD image stream ");
$ White = imagecolorallocate ($ im, 255,255,255 );
$ Start = microtime (true );
For ($ y = 0 ;y y <256; $ y ++ ){
For ($ x = 0; $ x <256; $ x ++ ){
If (random ($ setting) === 1 ){
Imagesetpixel ($ im, $ x, $ y, $ white );
}
}
}
$ Time = microtime (true)-$ start;
Header ("X-Exec-Time:". $ time );
Imagepng ($ im );
Imagedestroy ($ im );
/**
* Full Probability Calculation
*
* @ Param array $ p array ('A' => 0.5, 'B' => 0.2, 'c' => 0.4)
* @ Return string returns the key of the preceding array.
* @ Author Lukin
*/
Function random ($ ps ){
Static $ arr = array (); $ key = md5 (serialize ($ ps ));
If (! Isset ($ arr [$ key]) {
$ Max = array_sum ($ ps );
Foreach ($ ps as $ k => $ v ){
$ V = $ v/$ max * 10000;
For ($ I = 0; $ I <$ v; $ I ++) $ arr [$ key] [] = $ k;
}
}
Return $ arr [$ key] [mt_rand (0, count ($ arr [$ key])-1)];
}
?>
Black spots have a probability of 99%, and white spots have a probability of 1%. Test results: