色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

php數字游戲 計算24算法

算法思路:把每一個數字看做一個獨立的數學表達式,表達式之間加上標點符號組合成新表達式,一共組合4次,表達式之間的所有組合可以通過遞歸來實現.
代碼如下:
復制代碼 代碼如下:
<?php
/**
* A 24 maker
* @version 1.0.0
* @author laruence<laruence at yahoo.com.cn>
* @copyright (c) 2009 http://www.laruence.com
*/
class TwentyFourCal {
public $needle = 24;
public $precision = '1e-6';
function TwentyFourCal() {
}
private function notice($mesg) {
var_dump($mesg);
}
/**
* 取得用戶輸入方法
*/
public function calculate($operants = array()) {
try {
$this->search($operants, 4);
} catch (Exception $e) {
$this->notice($e->getMessage());
return;
}
$this->notice('can/'t compute!');
return;
}
/**
* 求24點算法php實現
*/
private function search($expressions, $level) {
if ($level == 1) {
$result = 'return ' . $expressions[0] . ';';
if ( abs(eval($result) - $this->needle) <= $this->precision) {
throw new Exception($expressions[0]);
}
}
for ($i=0;$i<$level;$i++) {
for ($j=$i+1;$j<$level;$j++) {
$expLeft = $expressions[$i];
$expRight = $expressions[$j];
$expressions[$j] = $expressions[$level - 1];
$expressions[$i] = '(' . $expLeft . ' + ' . $expRight . ')';
$this->search($expressions, $level - 1);
$expressions[$i] = '(' . $expLeft . ' * ' . $expRight . ')';
$this->search($expressions, $level - 1);
$expressions[$i] = '(' . $expLeft . ' - ' . $expRight . ')';
$this->search($expressions, $level - 1);
$expressions[$i] = '(' . $expRight . ' - ' . $expLeft . ')';
$this->search($expressions, $level - 1);
if ($expLeft != 0) {
$expressions[$i] = '(' . $expRight . ' / ' . $expLeft . ')';
$this->search($expressions, $level - 1);
}
if ($expRight != 0) {
$expressions[$i] = '(' . $expLeft . ' / ' . $expRight . ')';
$this->search($expressions, $level - 1);
}
$expressions[$i] = $expLeft;
$expressions[$j] = $expRight;
}
}
return false;
}
function __destruct() {
}
}
/* demo */
$tf = new TwentyFourCal();
$tf->calculate( array(4,8,8,8) );
?>

php技術php數字游戲 計算24算法,轉載需保留來源!

鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。

主站蜘蛛池模板: 阆中市| 海城市| 罗源县| 蒙阴县| 澄城县| 平陆县| 大港区| 平谷区| 顺昌县| 航空| 沁水县| 达日县| 庐江县| 宁武县| 晋江市| 靖远县| 枣阳市| 喀什市| 通化市| 新巴尔虎右旗| 安西县| 瑞金市| 平邑县| 东兰县| 嵩明县| 团风县| 五指山市| 修武县| 桦甸市| 大姚县| 商丘市| 朝阳县| 田林县| 望江县| 沿河| 长春市| 长兴县| 合川市| 大理市| 广宗县| 呼图壁县|