四虎精品视频-四虎精品成人免费网站-四虎黄色网-四虎国产视频-国产免费91-国产蜜臀97一区二区三区

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算法,轉載需保留來源!

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

主站蜘蛛池模板: cctv16体育台节目表| 二年级第一单元测试卷数学| 永刚| 米莎巴顿| douyincom| 无耻之徒豆瓣| 《爱的温暖》电影在线观看| free xxxx japan| 黛博拉·安沃尔| 丁丁历险记电影| 青山知可子冲绳草莽英雄1969| 电影《地狱天堂》鬼片| 《缱绻少年人》| 韩国三级播放| 山子高科股吧| 红色一号电影| 蹲踞式跳远教案| cctv6 节目表| 电影周处除三害| 陆廷威| 以下关于宏病毒说法正确的是| 让雷诺阿| 哗鬼住正隔篱| 电影名:《被囚禁的人》| 皮肤诊所| 免费看污视频在线观看| 电影《kiskisan》在线观看| 缺宅男女电视剧| 二年级拍手歌生字组词| 三年片电影| 来5566最新av在线电影| 黄昏光影| 二年级53天天练语文上册答案| kaya| 奇幻旅程| 皮肤诊所| 吴京电影全集完整版喜剧| 性女贞德| 国庆节安全公约| 海藻钙为啥不建议宝宝吃| 李采潭全部系列未删减|