js计算24点

时间:2023-03-08 17:44:37

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta name="Author" content="Netdream Ltd. - Ma Li" />
<head>
<title>Order by des...destiny</title>
<style type="text/css">
body
{
font-size: 12px;
font-family: Corbel;
}
.clear
{
clear: both;
}
.count
{
float: left;
margin-right: 20px;
margin-bottom: 10px;
}
input[name='txtnums']
{
width: 30px;
}
#txtshow
{
font-size: 16px;
font-weight: bold;
letter-spacing: 5px;
color: #ff0000;
}
</style>
<script type="text/javascript">
var opArr = new Array("+", "-", "*", "/");
var target = 24;
function Plan(arr, len, target) {
for (var i = 0; i < len; i++) {
for (var j = i + 1; j < len; j++) {
var ji = [arr[i], arr[j]];
arr[j] = arr[len - 1];
for (var q = 0; q < opArr.length; q++) {
arr[i] = '(' + ji[q % 2] + opArr[q] + ji[(!(q % 2) * 1)] + ')';
if (Plan(arr, len - 1, target)) {
return true;
}
}
arr[i] = ji[0]; arr[j] = ji[1];
}
}
return (len == 1) && (eval(arr[0]) == target);
}
function Result(arr, target) {
if (Plan(arr, arr.length, target)) {
var str = arr[0].substring(1, arr[0].length - 1);
return arr[0].substring(1, arr[0].length - 1) + "=" + String(target);
} else { return "Can't write:" + target; }
}
function show() {
var numsArr = new Array();
var nums = document.getElementsByName("txtnums");
var txttarget = document.getElementById('lblresult').innerHTML;
for (var i = 0; i < nums.length; i++) {
if (!CheckInt(nums[i].value)) {
alert('Please Check Your Input Value! The Value must be an integer~');
return false;
}
numsArr.push(nums[i].value);
}
document.getElementById("txtshow").innerHTML = Result(numsArr, txttarget);
}
function CheckInt(input) {
var reg1 = /^\d+$/;
return reg1.test(input);
}
</script>
</head>
<body>
<div class="count">
<input type="text" name="txtnums" maxlength="4" />
</div>
<div class="count">
<input type="text" name="txtnums" maxlength="4" />
</div>
<div class="count">
<input type="text" name="txtnums" maxlength="4" />
</div>
<div class="count">
<input type="text" name="txtnums" maxlength="4" />
</div>
<div id="lblresult" style="display: none;">
</div>
<script>
document.getElementById('lblresult').innerText = target;
</script>
<div class="count">
<input id="btnshow" type="button" value="Click!" onclick="show()" /><br />
</div>
<div class="clear">
</div>
<div id="txtshow">
</div>
</body>
</html>