PHP full probability calculation functions (optimized version) required for Webgame Development

Source: Internet
Author: User
PHP full probability calculation functions (optimized version) are essential for Webgame development. For more information, see.

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.