php数字游戏计算24算法
2023-06-13 09:14:34 时间
算法思路:把每一个数字看做一个独立的数学表达式,表达式之间加上标点符号组合成新表达式,一共组合4次,表达式之间的所有组合可以通过递归来实现.
代码如下:
复制代码代码如下:
代码如下:
<?php
/**
*A24maker
*@version1.0.0
*@authorlaruence<laruenceatyahoo.com.cn>
*@copyright(c)2009http://www.laruence.com
*/
classTwentyFourCal{
public$needle=24;
public$precision="1e-6";
functionTwentyFourCal(){
}
privatefunctionnotice($mesg){
var_dump($mesg);
}
/**
*取得用户输入方法
*/
publicfunctioncalculate($operants=array()){
try{
$this->search($operants,4);
}catch(Exception$e){
$this->notice($e->getMessage());
return;
}
$this->notice("can\"tcompute!");
return;
}
/**
*求24点算法PHP实现
*/
privatefunctionsearch($expressions,$level){
if($level==1){
$result="return".$expressions[0].";";
if(abs(eval($result)-$this->needle)<=$this->precision){
thrownewException($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;
}
}
returnfalse;
}
function__destruct(){
}
}
/*demo*/
$tf=newTwentyFourCal();
$tf->calculate(array(4,8,8,8));
?>
相关文章
- 笛卡尔积 php,PHP笛卡尔积实现算法示例
- 【UE4项目】类魂ARPG游戏实现
- 快速修改PHP镜像中的php.ini并生效 - wuuconix's blog
- PHP在MySQL中实现安全的表单提交(php表单提交mysql)
- MySQL数据库操作:用PHP实现(php操作mysql数据库)
- PHP与MySQL无缝对接,构建强大数据库应用(php整合mysql)
- 服务?探索Linux如何启动PHP服务(linux是否启动php)
- 使用PHP执行Linux脚本:简单而快速!(php执行linux脚本)
- 数据库使用PHP框架管理Oracle数据库(php框架oracle)
- Win10七月累积更新已修复3个严重问题:包括游戏性能等
- [下载]日常游戏优化和已知问题修复 AMD Radeon 21.2.1鸡血版驱动发布
- NFT游戏赛道再添竞争者 APENFT、WINkLink携手入局
- Linux安装PHP: 一步一步教你搞定(linux上安装php)
- 通过编写互动游戏学习 Bash
- PHP如何正确输出MySQL中文字符避免乱码?(php输出mysql乱码)
- 如何在Linux下顺利安装PHP?(在linux下安装php)
- PHP连接MSSQL实现注册功能(php注册写入mssql)
- PHP与MSSQL的良好配合,助力数据应用升级(php_mssql)
- Linux玩转游戏服务端的精彩世界(linux 游戏服务端)
- 游戏服务器利用Redis助你跨成功(游戏服务器使用redis)
- 谷歌携手 VR 初创公司 Improbable ,推出沉浸感游戏平台
- php网页游戏开发入门教程一(webgame+design)
- php数据结构与算法(PHP描述)查找与二分法查找
- Linux+php+apache+oracle环境搭建之CentOS下源码编译安装PHP