演算法思路:把每一個數字看做一個獨立的數學表達式,表達式之間加上標點符號組合成新表達式,一共組合4次,表達式之間的所有組合可以通過遞歸來實現.
程式碼如下:
. 程式碼如下:
/**
* 24 位創作者
* @version 1.0.0
* @author laruence
* @copyright (c) 2009 http://www.laruence.com
* @copyright (c) 2009 http://www.laruence.com
*/
class TwentyFourCal {
public $needle = 240508o; () {
}
private function notice($mesg) {
var_dump($mesg);
}
/**
* 取得使用者輸入方式
*/
public function calculate($oper
/**
* 求24點演算法PHP實作
*/
public function calculate($oper) = this->search($operants, 4);
} catch (Exception $e) {
$this->notice($e->getMessage());
return;
}
$this->notice(can 't compute!');
return;
}
/**&*/
private function search($expressions, $level) {
if ($level == 1) {
. $expressions[0] . ';';
if ( abs(eval($result) - $this->needle) precision) {
throw new Exception($expressions[0]);
throw new Exception($expressions[0]);
throw new Exception($expressions[0]);
throw new Exception($expressions[0]); }
}
for ($i=0;$ifor ($j=$i+1;$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);
$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, $等級 - 1);
}
$expressions[$i] = $expLeft;
$expressions[$j] = $expRight;
}
}
/* demo */
$tf = new TwentyFourCal();
$tf->calculate( array(4,8,8,8) );
?>
以上是數字遊戲計算以上是數字遊戲計算以上是數字遊戲的內容,php更多相關文章請關注PHP中文網(www.php.cn)!