求: 三个5,一个1组成的数学表达式的结果=24, 结果:(5-1/5)*5=24
<?php
set_time_limit(0);
$values = array(1, 5, 5, 5);
$result = 24;
$list = array();
echo "<pre>";
makevalue($values);
print_r($list);
function makevalue($values, $set=array())
{
$words = array("+", "-", "*", "/");
if(sizeof($values)==1)
{
$set[] = array_shift($values);
return makespecial($set);
}
foreach($values as $key=>$value)
{
$tmpvalues = $values;
unset($tmpvalues[$key]);
foreach($words as $word)
{
makevalue($tmpvalues, array_merge($set, array($value, $word)));
}
}
}
function makespecial($set)
{
$size = sizeof($set);
if($size<=3 || !in_array("/", $set) && !in_array("*", $set))
{
return makeresult($set);
}
for($len=3; $len<$size-1; $len+=2)
{
for($start=0; $start<$size-1; $start+=2)
{
if(!($set[$start-1]=="*" || $set[$start-1]=="/" || $set[$start+$len]=="*" || $set[$start+$len]=="/"))
continue;
$subset = array_slice($set, $start, $len);
if(!in_array("+", $subset) && !in_array("-", $subset))
continue;
$tmpset = $set;
array_splice($tmpset, $start, $len-1);
$tmpset[$start] = "(".implode("", $subset).")";
makespecial($tmpset);
}
}
}
function makeresult($set)
{
global $result, $list;
$str = implode("", $set);
@eval("/$num=$str;");
if($num==$result && !in_array($str, $list))
$list[] = $str;
}
?>
新闻热点
疑难解答