我有以下代码来生成给定数字的排列。问题是,如果我尝试生成5位数以上的排列,那么它将永远运行。如何优化此程序以在浏览器中显示结果。
<html>
<script>
function permute(level, permuted, used, original) {
var length = original.length;
if (level == length) {
//System.out.println(permuted);
document.getElementById("nmbrs").innerHTML = document.getElementById("nmbrs").innerHTML + "<br />" +permuted
} else {
for (var i = 0; i < length; i++) {
if (!used[i]) {
used[i] = true;
permute(level + 1, permuted + original[i],
used, original);
used[i] = false;
}
}
}
}
function executeP(){
var s = ['0','1','2','7'];
document.getElementById("nmbrs").innerHTML = "";
var length = eval(document.getElementById("num").value);
/*for(var i=length-1;i>=0;i--){
var used = [false, false, false, false];
permute(i, "", used, s);
}*/
var newArray = ['0','1','2','7'];
if(length > 4){
var newIte = length - 4;
do{
newArray.push(s[(newIte-1) % 4]);
newIte--;
}while(newIte>0);
}
var used = [false, false, false, false,false, false, false, false,false, false, false, false];
permute(newArray.length-length, "", used, newArray);
}
</script>
<body>
<input type="text" id="num" />
<input type="button" value="Generate Num" onclick="executeP()" />
<div id="nmbrs" ></div>
</body>
</html>
答案 0 :(得分:1)
您的主要问题是您经常操作DOM,这很昂贵。相反,将结果存储在临时位置,然后生成要使用的HTML,然后将其附加到DOM。
这是您的网页/脚本的修改版本,显示我的意思,并轻松生成长度为8+的排列;
<html>
<script>
var results = [];
function permute(level, permuted, used, original) {
var length = original.length;
if (level == length) {
results.push(permuted);
} else {
for (var i = 0; i < length; i++) {
if (!used[i]) {
used[i] = true;
permute(level + 1, permuted + original[i],
used, original);
used[i] = false;
}
}
}
}
function executeP(){
var s = ['0','1','2','7'];
document.getElementById("nmbrs").innerHTML = "";
var length = eval(document.getElementById("num").value);
var newArray = ['0','1','2','7'];
if(length > 4) {
var newIte = length - 4;
do {
newArray.push(s[(newIte-1) % 4]);
newIte--;
} while (newIte>0);
}
var used = [false, false, false, false,false, false, false, false,false, false, false, false];
permute(newArray.length-length, "", used, newArray);
var resultHtml = "";
var resultLength = results.length;
for (var i = 0; i < resultLength; i++) {
resultHtml += results[i];
resultHtml += "<br/>";
}
document.getElementById("nmbrs").innerHTML = resultHtml;
}
</script>
<body>
<input type="text" id="num" />
<input type="button" value="Generate Num" onclick="executeP()" />
<div id="nmbrs" ></div>
</body>
</html>
答案 1 :(得分:0)
您的递归会将所有内容保留在堆栈中。您需要以某种方式使其尾递归(从循环中删除递归调用并以某种方式将其移动到函数的末尾)或将所有递归调用推送到您自己的堆栈,这样您至少可以让函数死掉。所有这些都假定浏览器足够聪明,可以检测到它也是尾递归的,所以IE好运。