Php digital game Computing 24 algorithm. Algorithm idea: think of every number as an independent mathematical expression. the expression is combined with punctuation to form a new expression. it is combined four times in total. all the combinations between expressions can be considered as an algorithm idea: each number is considered as an independent mathematical expression. a punctuation symbol is added between expressions to form a new expression. the expression is combined four times in total. all the combinations between expressions can be implemented through recursion.
The code is as follows:
The code is as follows:
/**
* A 24 maker
* @ Version 1.0.0
* @ Author laruence
* @ 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 );
}
/**
* Obtain user input methods
*/
Public function calculate ($ operants = array ()){
Try {
$ This-> search ($ operants, 4 );
} Catch (Exception $ e ){
$ This-> notice ($ e-> getMessage ());
Return;
}
$ This-> notice ('Can \'t compute! ');
Return;
}
/**
* Seek the 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 ));
?>
...