Three 5, one 1 The result of a mathematical expression = 24, Result: (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;
}
?>