<?php
class calculate24 {
public $result = null;
public function generate() {
$nums = array(
mt_rand(1, 13),
mt_rand(1, 13),
mt_rand(1, 13),
mt_rand(1, 13),
);
echo implode(' ', $nums) . '<br />';
$this->is24($nums);
echo $this->getResult();
}
public function is24($nums, $str = '') {
if (!$nums || !is_array($nums) || array_sum($nums) <= 8) {
return false;
}
$count = count($nums);
for ($i=0; $i<$count; $i++) {
for($j=$i+1; $j<$count; $j++) {
$result = $this->calculateTwo($nums[$i], $nums[$j]);
if ($count == 2) {
if (in_array(24, $result)) {
$this->result = $str . array_search(24, $result) . '=' . 24 . '<br />';
return true;
}
} elseif ($count > 2) {
foreach ($result as $k => $r) {
$tmp_str = $str;
$tmp_nums = $nums;
unset($tmp_nums[$i], $tmp_nums[$j]);
array_unshift($tmp_nums, $r);
$tmp_str .= $k . '=' . $r . '<br />';
if ($this->is24(array_values($tmp_nums), $tmp_str)) {
return true;
}
}
}
}
}
return false;
}
public function calculateTwo($num1, $num2) {
$result = array();
$result["{$num1}+{$num2}"] = $num1 + $num2;
$result["{$num1}*{$num2}"] = $num1 * $num2;
$result["{$num1}-{$num2}"] = $num1 - $num2;
$result["{$num2}-{$num1}"] = $num2 - $num1;
if ($num2 != 0 && $num1 % $num2 === 0) {
$result["{$num1}/{$num2}"] = $num1 / $num2;
} elseif ($num1 != 0 && $num2 % $num1 === 0) {
$result["{$num2}/{$num1}"] = $num2 / $num1;
}
return array_unique($result);
}
public function getResult() {
return $this->result;
}
}
$calculate24 = new calculate24();
$calculate24->generate();
exit;