自己写的脚本,简单用用吧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>24点游戏</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 20px;
}
form input {
margin: 5px;
width: 50px;
}
#result, #steps {
margin-top: 20px;
font-size: 1.2em;
}
</style>
</head>
<body>
<h1>24点游戏</h1>
<form id="numbersForm">
<input type="number" id="num1" required>
<input type="number" id="num2" required>
<input type="number" id="num3" required>
<input type="number" id="num4" required>
<button type="submit">计算</button>
</form>
<div id="result"></div>
<div id="steps"></div>
<script>
document.getElementById('numbersForm').addEventListener('submit', function(event) {
event.preventDefault();
const numbers = [
parseFloat(document.getElementById('num1').value),
parseFloat(document.getElementById('num2').value),
parseFloat(document.getElementById('num3').value),
parseFloat(document.getElementById('num4').value)
];
const result = document.getElementById('result');
const steps = document.getElementById('steps');
const [solved, solution] = find24(numbers);
result.textContent = solved ? '有解法!' : '无解法。';
steps.textContent = solved ? `解法步骤: ${solution}` : '';
});
function find24(numbers) {
const target = 24;
const operators = ['+', '-', '*', '/'];
let solution = '';
const evaluate = (a, b, op) => {
switch(op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return b !== 0 ? a / b : NaN;
default: return NaN;
}
};
const solve = (nums, path) => {
if (nums.length === 1) {
if (Math.abs(nums[0] - target) < 1e-6) {
solution = path;
return true;
}
return false;
}
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
if (i !== j) {
const remaining = nums.filter((_, index) => index !== i && index !== j);
for (const op of operators) {
const result = evaluate(nums[i], nums[j], op);
if (isFinite(result)) {
const expression = `(${nums[i]} ${op} ${nums[j]})`;
if (solve([...remaining, result], `${path} -> ${expression} = ${result}`)) {
return true;
}
}
}
}
}
}
return false;
};
return [solve(numbers, ''), solution];
}
</script>
</body>
</html>