算法思路:把每一个数字看做一个独立的数学表达式,表达式之间加上标点符号组合成新表达式,一共组合4次,表达式之间的所有组合可以通过递归来实现.
代码如下:
<BR><?php <BR>/** <BR>* A 24 maker <BR>* @version 1.0.0 <BR>* @author laruence <BR>* @copyright (c) 2009 http://www.laruence.com <BR>*/ <BR>class TwentyFourCal { <BR>public $needle = 24; <BR>public $precision = '1e-6'; <BR>function TwentyFourCal() { <BR>} <BR>private function notice($mesg) { <BR>var_dump($mesg); <BR>} <BR>/** <BR>* 取得用户输入方法 <BR>*/ <BR>public function calculate($operants = array()) { <BR>try { <BR>$this->search($operants, 4); <BR>} catch (Exception $e) { <BR>$this->notice($e->getMessage()); <BR>return; <BR>} <BR>$this->notice('can\'t compute!'); <BR>return; <BR>} <BR>/** <BR>* 求24点算法PHP实现 <BR>*/ <BR>private function search($expressions, $level) { <BR>if ($level == 1) { <BR>$result = 'return ' . $expressions[0] . ';'; <BR>if ( abs(eval($result) - $this->needle) precision) { <BR>throw new Exception($expressions[0]); <BR>} <BR>} <BR>for ($i=0;$i<$level;$i++) { <BR>for ($j=$i+1;$j<$level;$j++) { <BR>$expLeft = $expressions[$i]; <BR>$expRight = $expressions[$j]; <BR>$expressions[$j] = $expressions[$level - 1]; <BR>$expressions[$i] = '(' . $expLeft . ' + ' . $expRight . ')'; <BR>$this->search($expressions, $level - 1); <BR>$expressions[$i] = '(' . $expLeft . ' * ' . $expRight . ')'; <BR>$this->search($expressions,<span>!本文来源gaodai#ma#com搞*!代#%^码网5</span><pre>搞gaodaima代码
$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) );
?>