scu*_*ver 5 javascript string combinations permutation
我正在尝试列出所有三个字母的排列,这是我的代码 -
window.permute = function(){
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var searchTerm ="aaa";
var position = 2;
changeString(searchTerm, position);
}
window.changeString = function(searchTerm, position){
if (position <0){
alert(newString);
return;
}
var alphabet = "abcdefghijklmnopqrstuvwxyz"
for (j=0; j < 26;j++){
var newString = searchTerm.substr(0, position) + alphabet[j] + searchTerm.substr(position+1);
var newPosition = position -1;
changeString(newString,newPosition);
}
return;
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,我不知道为什么 - 有人可以帮忙吗?
alert(newString);
Run Code Online (Sandbox Code Playgroud)
newString没有在那里定义。相反,您应该使用传递的参数:
alert(searchTerm);
Run Code Online (Sandbox Code Playgroud)
编辑:我不完全确定你的方法。看起来过于复杂了。这似乎有效。我知道您宁愿让自己的代码工作,但这也许可以帮助您解决问题。我不太明白你的substr意思。
var alphabet = "abc"; // shortened to save time
function permute(text) {
if(text.length === 3) { // if length is 3, combination is valid; alert
console.log(text); // or alert
} else {
var newalphabet = alphabet.split("").filter(function(v) {
return text.indexOf(v) === -1;
}); // construct a new alphabet of characters that are not used yet
// because each letter may only occur once in each combination
for(var i = 0; i < newalphabet.length; i++) {
permute(text + newalphabet[i]); // call permute with current text + new
// letter from filtered alphabet
}
}
}
permute("");
Run Code Online (Sandbox Code Playgroud)
这将导致调用以下内容:
permute("");
permute("a");
permute("ab");
permute("abc"); // alert
permute("ac");
permute("acb"); // alert
permute("b");
// ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2553 次 |
| 最近记录: |