21,886
社区成员
发帖
与我相关
我的任务
分享
<?php
function Calculate24Point($a, &$r, &$ex, $n)
{
$ex2 = $ex;
if($n == 1)
{
if( abs($a[0] - 24) <= 0.000001 )
{
$r[] = $ex[0];
return true;
} else {
return false;
}
}
for($i = 0; $i < $n; $i ++)
{
for($j = $i + 1; $j < $n; $j ++)
{
$x = $a[$i];
$y = $a[$j];
$a[$j] = $a[$n - 1];
$exa = $ex[$i];
$exb = $ex[$j];
$ex[$j] = $ex[$n - 1];
$a[$i] = $x + $y;
$ex[$i] = "($exa + $exb)";
if(Calculate24Point($a, $r, $ex, $n - 1))
{
return true;
}
$a[$i] = $x - $y;
$ex[$i] = "($exa - $exb)";
if(Calculate24Point($a, $r, $ex, $n - 1))
{
return true;
}
$a[$i] = $y - $x;
$ex[$i] = "($exb - $exa)";
if(Calculate24Point($a, $r, $ex, $n - 1))
{
return true;
}
$a[$i] = $x * $y;
$ex[$i] = "($exa * $exb)";
if(Calculate24Point($a, $r, $ex, $n - 1))
{
return true;
}
if($y != 0)
{
$a[$i] = $x / $y;
$ex[$i] = "($exa / $exb)";
if(Calculate24Point($a, $r, $ex, $n - 1))
{
return true;
}
}
if($x != 0)
{
$a[$i] = $y / $x;
$ex[$i] = "($exb / $exa)";
if(Calculate24Point($a, $r, $ex, $n - 1))
{
return true;
}
}
$a[$i] = $x;
$a[$j] = $y;
$ex = $ex2;
}
}
return false;
}
$a[0] = $ex[0] = $_REQUEST['a1'];
$a[1] = $ex[1] = $_REQUEST['a2'];
$a[2] = $ex[2] = $_REQUEST['a3'];
$a[3] = $ex[3] = $_REQUEST['a4'];
if(Calculate24Point($a, $result, $ex, count($a)))
{
for($i = 0; $i < count($result); $i ++)
{
echo "Answer: " . $result[$i] . "<br>\r\n";
}
} else {
echo "No Answer.";
}
?>
<form action="" method="POST">
<input type="text" size="8" name="a1" value="<?php echo $_REQUEST['a1'];?>"/>
<input type="text" size="8" name="a2" value="<?php echo $_REQUEST['a2'];?>"/>
<input type="text" size="8" name="a3" value="<?php echo $_REQUEST['a3'];?>"/>
<input type="text" size="8" name="a4" value="<?php echo $_REQUEST['a4'];?>"/>
<input type="submit" value="Calculate"/>
</form>