http://community.csdn.net/Expert/topic/3735/3735144.xml?temp=8.680362E-02
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Javascript版 v1.0</title>
<META HTTP-EQUIV="REFRESH" CONTENT=10; URL=*.*>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
</head>
<body>
<br>
计算24点(加、减、乘、除、括号) Javascript版 v1.0<br><br>
<br><br><br><br>
<form>
<div align=center>
时间限制(10秒)<br><br>
<input type="text" name="fa" value="<%=l1%>" size="10">
<input type="text" name="fb" value="<%=l2%>" size="10">
<input type="text" name="fc" value="<%=l3%>" size="10">
<input type="text" name="fd" value="<%=l4%>" size="10">
<br><br><input type="button" name="btn" onclick="javascript:funCount()" value="查看答案 ">
</div></form>
<script language="JavaScript">
function log(str)
{
document.write("<br>"+str);
}
//生成计算表达式
function genExpress(exp,a,b,c,d,m1,m2,m3)
{
var
exp=exp.replace("a",a);
exp=exp.replace("b",b);
exp=exp.replace("c",c);
exp=exp.replace("d",d);
exp=exp.replace("m1",m1);
exp=exp.replace("m2",m2);
exp=exp.replace("m3",m3);
return exp;
}
var answer = new Array();//正确答案的表达式
var counter = 0;//答案的个数
//测试表达式是否正确
function test(expn,a,b,c,d,m1,m2,m3)
{
var exp;
var ret;
exp = genExpress(expn,a,b,c,d,m1,m2,m3);//生成计算表达式
eval("ret = "+exp);
if ( ret - 24 < 0.1 && ret - 24 >= 0 )
{
exp = exp.replace(";","");
exp = replaceAll(exp,"*","×");
exp = replaceAll(exp, "/","÷");
var have = false;
for ( var i=0; i<counter; i++)
{
if ( exp == answer[i] )
{
have = true;
break;
}
}
if ( !have )
{
answer[counter] = exp;
counter++;
log("<font color=red><b>"+counter+": "+exp+"</b></font>");
}
}
}
function replaceAll (streng, soeg, erstat)
{
var st = streng;
if (soeg.length == 0)
return st;
var idx = st.indexOf(soeg);
while (idx >= 0)
{
st = st.substring(0,idx) + erstat + st.substr(idx+soeg.length);
idx = st.indexOf(soeg);
}
return st;
}
var n = new Array();//四个数字
//接收四个输入框的数字,调用主程序
function funCount()
{
n[0] = document.forms[0].fa.value;
n[1] = document.forms[0].fb.value;
n[2] = document.forms[0].fc.value;
n[3] = document.forms[0].fd.value;
if ( n[0] > 0 && n[1] > 0 && n[2] > 0 && n[3] > 0 && n[0] < 14 && n[1] < 14 && n[2] < 14 && n[3] < 14 )
{
log("<font size=5><b>"+n[0]+", "+n[1]+", "+n[2]+", "+n[3]+"的24点答案:</b></font><br>");
log("<input type='button' ><br>");
funMain();
if ( counter == 0 )
{
log("没有答案!");
}
}
else
{
alert("输入错误!");
}
}
//主程序
function funMain()
{
var m = new Array();
//四种运算符
m[0] = "+";
m[1] = "-";
m[2] = "*"