Home > php教程 > php手册 > php计算24点游戏

php计算24点游戏

WBOY
Release: 2016-06-21 09:05:02
Original
994 people have browsed it

求: 三个5,一个1组成的数学表达式的结果=24,   结果:(5-1/5)*5=24

 set_time_limit(0);
 $values = array(1, 5, 5, 5);
 $result = 24;

 $list = array();

 echo "

";<br> makeValue($values);<br> print_r($list);<p> function makeValue($values, $set=array())<br> {<br>  $words = array("+", "-", "*", "/");<br>  if(sizeof($values)==1)<br>  {<br>   $set[] = array_shift($values);<br>   return makeSpecial($set);<br>  }<br>  foreach($values as $key=>$value)<br>  {<br>   $tmpValues = $values;<br>   unset($tmpValues[$key]);<br>   foreach($words as $word)<br>   {<br>    makeValue($tmpValues, array_merge($set, array($value, $word)));<br>   }<br>  }<br> } <br> <br> function makeSpecial($set)<br> {<br>  $size = sizeof($set);</p><p>  if($size  {<br>   return makeResult($set);<br>  }</p><p>  for($len=3; $len  {<br>   for($start=0; $start   {<br>    if(!($set[$start-1]=="*" || $set[$start-1]=="/" || $set[$start+$len]=="*" || $set[$start+$len]=="/"))<br>     continue;<br>    $subSet = array_slice($set, $start, $len);<br>    if(!in_array("+", $subSet) && !in_array("-", $subSet))<br>     continue;<br>    $tmpSet = $set;<br>    array_splice($tmpSet, $start, $len-1);<br>    $tmpSet[$start] = "(".implode("", $subSet).")";<br>    makeSpecial($tmpSet); <br>   }<br>  }<br> } </p><p><br> function makeResult($set)<br> {<br>  global $result, $list;<br>     $str = implode("", $set);<br>  @eval("\$num=$str;");<br>  if($num==$result && !in_array($str, $list))<br>   $list[] = $str;<br> } </p><p>?><br></p>
            <p style="width:100%;text-align:center;margin:10px 0">

<br>
<br>

</p><p style="width:100%;text-align:center;margin:10px 0">

            </p><p class="clear"></p>

           
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template