PHP全概率运算函数(优化版) Webgame开发必备
作者:bea
代码如下: <?php $setting = array( // 黑色概率 0 => 0.99, // 白色概率 1 => 0.01, ); // Requires the GD Library header("Content-type: image/png"); $im = imagecreatetruecolor(256, 256) or die("Cannot Initialize new GD image stream");
代码如下:
<?php
$setting = array(
// 黑色概率
0 => 0.99,
// 白色概率
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<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);
/**
* 全概率计算
*
* @param array $p array('a'=>0.5,'b'=>0.2,'c'=>0.4)
* @return string 返回上面数组的key
* @author Lukin <my@lukin.cn>
*/
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)];
}
?>
黑点出现概率99%,白点出现概率1%,测试结果:
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- php入门学习知识点五 关于php数组的几个基本操作
- php入门学习知识点四 PHP正则表达式基本应用
- php入门学习知识点三 PHP上传
- php入门学习知识点二 PHP简单的分页过程与原理
- php入门学习知识点一 PHP与MYSql连接与查询
- php自定义函数call_user_func和call_user_func_array详解
- PHP 获取MySQL数据库里所有表的实现代码
- PHP setcookie设置Cookie用法(及设置无效的问题)
- php中使用explode查找某个字符是否存在的方法
- php array_push()数组函数:将一个或多个单元压入数组的末尾(入栈)
- php array_pop()数组函数将数组最后一个单元弹出(出栈)
- php array_map()数组函数使用说明
- php array_walk() 数组函数
- 7个超级实用的PHP代码片段
- php函数的常用方法及注意之处小结
- PHP 数据结构 算法描述 冒泡排序 bubble sort
- PHP中获取变量的变量名的一段代码的bug分析
- PHP的一个基础知识 表单提交
- php与mysql建立连接并执行SQL语句的代码