最新国产好看的视频,伊人天堂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á)式之間的所有組合可以通過遞歸來實(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)論

芜湖市| 辽阳市| 明水县| 资源县| 墨玉县| 宽甸| 宣化县| 定远县| 巴彦淖尔市| 磐安县| 饶阳县| 怀安县| 阳山县| 当涂县| 永年县| 盐津县| 镇平县| 云霄县| 哈密市| 海盐县| 中西区| 达日县| 竹山县| 兴义市| 桐庐县| 凌云县| 教育| 海门市| 宁乡县| 镇巴县| 诸暨市| 黔江区| 大连市| 长岭县| 台山市| 娄底市| 五指山市| 南丰县| 隆回县| 漯河市| 利辛县|