Algorithm idea: Each number as a separate mathematical expression, the expression plus punctuation group synthesis of new expressions, a total combination of 4 times, the expression of all combinations can be realized by recursion.
The code is as follows:
Copy Code code as follows:
<?php
/**
* A Maker
* @version 1.0.0
* @author laruence<laruence at yahoo.com.cn>
* @copyright (c) 2009 http://www.laruence.com
*/
Class Twentyfourcal {
Public $needle = 24;
Public $precision = ' 1e-6 ';
function twentyfourcal () {
}
Private Function Notice ($MESG) {
Var_dump ($MESG);
}
/**
* Get user Input Method
*/
Public function Calculate ($operants = Array ()) {
try {
$this->search ($operants, 4);
catch (Exception $e) {
$this->notice ($e->getmessage ());
Return
}
$this->notice (' can\ ' t compute! ');
Return
}
/**
* Find 24 point algorithm PHP implementation
*/
Private Function Search ($expressions, $level) {
if ($level = = 1) {
$result = ' return '. $expressions [0]. ';';
if (ABS (eval ($result)-$this->needle) <= $this->precision) {
throw new Exception ($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;
}
}
return false;
}
function __destruct () {
}
}
/* Demo * *
$TF = new Twentyfourcal ();
$TF->calculate (Array (4,8,8,8));
?>