Custom range, custom operator, custom number of operations. So cool
- /**
- * Description of QuestionEngine
- * A question engine
- *
- * @author lyc
- * @copyright (c) 2013, Unary Inc.
- */
- class QuestionEngine {
-
- /**
- * Question scope
- * @var string $scope
- */
- public $scope = array(1, 100);
-
- /**
- * Operators included, if there are multiple operators, the question will be mixed
- * @var string $operators
- */
- public $operators = '+-';
-
- /**
- * Number of operations
- * @var int
- */
- public $optTimes = 1;
-
- public function generate() {
- //Generate a set of values according to the number of operations
- start:
- for ($index = 0; $index < $this->optTimes + 1; $index++) {
- $elements[] = $this->randomValue();
- }
- $operatorType = strlen( $this->operators); //There are several operators to choose from
- //Start assembling the calculation
- $question = '';
- for ($index = 0; $index < count($elements); $index++ ) {
- $question.=' ' . $elements[$index] . ' '; //Put a number in
- if ($index < count($elements) - 1)//If it is not the last number, Add an operator at the end
- $question.=substr($this->operators, mt_rand(0, $operatorType - 1), 1);
- }
-
- eval('$anwser = ' . $question . '; ');
- if ($anwser < 0) { //Exclude the case where the result is a negative number
- $elements = array();
- goto start; //Requires PHP5.3 support
- }
- echo "$question= " . $anwser;
- }
- /**
- * Generate a random value within a range
- *
- * @return int
- */
- protected function randomValue() {
- return mt_rand($this->scope[0], $this->scope[1]);
- }
-
- }
-
Copy code
- include 'QuestionEngine.class.php';
- $hello = new QuestionEngine();
- $hello->generate();
- ?>
-
- Result: 26 + 85 = 111
Copy code
|