最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

php數(shù)字游戲 計(jì)算24算法

 更新時(shí)間:2012年06月10日 18:39:46   作者:  
輸入任意4個(gè)數(shù)字,然后對(duì)其進(jìn)行+-*/組合,所得數(shù)學(xué)表達(dá)式值等于24
算法思路:把每一個(gè)數(shù)字看做一個(gè)獨(dú)立的數(shù)學(xué)表達(dá)式,表達(dá)式之間加上標(biāo)點(diǎn)符號(hào)組合成新表達(dá)式,一共組合4次,表達(dá)式之間的所有組合可以通過(guò)遞歸來(lái)實(shí)現(xiàn).
代碼如下:
復(fù)制代碼 代碼如下:

<?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點(diǎn)算法PHP實(shí)現(xiàn)
*/
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) );
?>

相關(guān)文章

最新評(píng)論

嫩江县| 武安市| 铜陵市| 新昌县| 策勒县| 乌海市| 保康县| 夏邑县| 青阳县| 犍为县| 平塘县| 中方县| 钟祥市| 河东区| 银川市| 宁津县| 四会市| 富裕县| 会昌县| 温宿县| 阿城市| 芒康县| 浏阳市| 高清| 五莲县| 阜宁县| 化州市| 光泽县| 岐山县| 浦东新区| 二手房| 闽侯县| 弋阳县| 永平县| 扎兰屯市| 邵阳市| 玉树县| 河北省| 黄大仙区| 宝坻区| 开远市|