• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

php数字游戏 计算24算法_php实例

php 搞代码 4年前 (2022-01-25) 12次浏览 已收录 0个评论

算法思路:把每一个数字看做一个独立的数学表达式,表达式之间加上标点符号组合成新表达式,一共组合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) );
?>


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:php数字游戏 计算24算法_php实例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址