Discuz教程网

PHP全概率运算函数(优化版) Webgame开发必备

[复制链接]
authicon dly 发表于 2011-8-31 11:55:36 | 显示全部楼层 |阅读模式
代码如下:

  1. <?php
  2. $setting = array(
  3. // 黑色概率
  4. 0 => 0.99,
  5. // 白色概率
  6. 1 => 0.01,
  7. );
  8. // Requires the GD Library
  9. header("Content-type: image/png");
  10. $im = imagecreatetruecolor(256, 256) or die("Cannot Initialize new GD image stream");
  11. $white = imagecolorallocate($im, 255, 255, 255);
  12. $start = microtime(true);
  13. for ($y=0; $y<256; $y++) {
  14. for ($x=0; $x<256; $x++) {
  15. if (random($setting) === 1) {
  16. imagesetpixel($im, $x, $y, $white);
  17. }
  18. }
  19. }
  20. $time = microtime(true) - $start;
  21. header("X-Exec-Time: ".$time);
  22. imagepng($im);
  23. imagedestroy($im);

  24. /**
  25. * 全概率计算
  26. *
  27. * @param array $p array('a'=>0.5,'b'=>0.2,'c'=>0.4)
  28. * @return string 返回上面数组的key
  29. * @author Lukin <my@lukin.cn>
  30. */
  31. function random($ps){
  32. static $arr = array(); $key = md5(serialize($ps));
  33. if (!isset($arr[$key])) {
  34. $max = array_sum($ps);
  35. foreach ($ps as $k=>$v) {
  36. $v = $v / $max * 10000;
  37. for ($i=0; $i<$v; $i++) $arr[$key][] = $k;
  38. }
  39. }
  40. return $arr[$key][mt_rand(0,count($arr[$key])-1)];
  41. }
  42. ?>
复制代码

黑点出现概率99%,白点出现概率1%,测试结果:
20110704222224776.png




上一篇:PHP写杨辉三角实例代码
下一篇:PHP守护进程 加linux命令nohup实现任务每秒执行一次
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-2 20:16

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表