问题是: 把五个数字 56789, 放到 [][][] * [][], 令结果最大.
第一种:
<html>
<head>
<title> New Document </title>
</head>
<body>
<script language="JavaScript">
<!--
var arr = [5,6,7,8,9];
function lop(j)
{
if(j>0)
{
var ss = lop(j-1);
var px = "";
var oo = "$1"+arr[j]+"$2";
for(var k=0; k<=j; k++)
{
var re = new RegExp("(\\d{"+k+"})(\\d*;)","g");
px += ss.replace(re,oo);
}
return px;
}
else
return arr[0]+";";
}
var maxStr = "";
var max = 0;
lop(arr.length-1).replace(/(\d{3})(\d{2})/g,function(s,a,b)
{
var n = parseInt(a,10) * parseInt(b,10);
var txt = a+"*"+b+"="+n;
document.write(txt,"<br>");
if(n>max)
{
max=n;
maxStr=txt;
}
});
document.write("<br>最大结果为:",maxStr);
//-->
</script>
</body>
</html>
第二种:
<script>
function find(array, len1, len2)
{
array = array.slice().sort().slice(array.length - len1 - len2);
var ret = [[], []];
var p = len1 < len2 ? 0 : 1;
var n = len1 < len2 ? len1 : len2;
for (var i = 0; i < n; ++i)
{
var d1 = array.pop(), d2 = array.pop();
ret[p].push(d1);
ret[1 - p].push(d2);
p = d1 == d2 ? p : 1 - p;
}
p = len1 < len2 ? 1 : 0;
ret[p] = ret[p].concat(array.reverse());
return [ret[0].join(""), ret[1].join("")];
}
var r = find([5, 6, 7, 8, 9], 3, 2);
alert(r[0] + " * " + r[1] + " = " + r[0] * r[1]);
</script>
posted on 2006-04-03 15:00
汪杰 阅读(189)
评论(0) 编辑 收藏 引用 所属分类:
hengxing网站js