PHP歷理 做一個計算24點的功能

onestopweb發表於2024-05-31

注意:有些計算24點的數字無法計算出來。不建議使用。

<?php
function calculate24($nums) {
    $operators = ['+', '-', '*', '/'];

    $combinations = [];
    foreach ($nums as $num1) {
        foreach ($nums as $num2) {
            if ($num1!= $num2) {
                foreach ($nums as $num3) {
                    if ($num1!= $num3 && $num2!= $num3) {
                        foreach ($nums as $num4) {
                            if ($num1!= $num4 && $num2!= $num4 && $num3!= $num4) {
                                foreach ($operators as $op1) {
                                    foreach ($operators as $op2) {
                                        foreach ($operators as $op3) {
                                            $expression = "((($num1 $op1 $num2) $op2 $num3) $op3 $num4)";
                                            $result = eval("return ". $expression. ";");
                                            if ($result == 24) {
                                                $combinations[] = $expression;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return $combinations;
}
$numbers = [4, 6, 8, 2];
$combinations = calculate24($numbers);
if (!empty($combinations)) {
    echo "以下組合可以得到 24:<br>";
    foreach ($combinations as $combination) {
        echo $combination. "<br>";
    }
} else {
    echo "無法透過這些數字得到 24。";
}
?>

效果圖:

相關文章