我一直在使用来自JSFiddle的这个this thread,但无法弄清楚1)如何让它与多个单词一起使用,例如我输入
applebanana
获取输出
苹果香蕉,香蕉苹果
2)因此,如果我将变量更改为包含多个单词字符串,例如:
var dictionary = [
"apple",
"banana",
"orange",
"pear",
"mandarin orange" ];
我可以输入
mandarinorange
获取输出
橘子
以下是JSFiddle上面的相关代码
var maxCount = 10000;
var dictionary = [
"apple",
"banana",
"orange",
"pear",
"watermelon"
];
function isValidWord(word) {
for(var i = 0, n = dictionary.length; i < n; i++) {
if(word === dictionary[i]) {
return true;
}
}
return false;
}
/**
Generates all of the anagrams using a dictionary and an exclusion list read from
an HTML form.
*/
function runAnagramGenerator(anagramString, excludesString, tout) {
var excludes = getExclusionList(excludesString);
var anagrams = [];
generateAnagrams("", anagramString, excludes, anagrams);
//Remove duplicates
uniqueAnagramList = anagrams.filter(function(elem, pos, self) {
return self.indexOf(elem) == pos;
});
console.log('Anagrams: ' + uniqueAnagramList.length);
tout.value = "";
for(var i = 0, n = uniqueAnagramList.length; i < n; i++) {
tout.value += uniqueAnagramList[i] + "\r\n";
}
}
function getExclusionList(excludesString) {
var excludes = [];
if (excludesString != "") {
var excludesArray = excludesString.split(",");
for(var i = 0, n = excludesArray.length; i < n; i++) {
excludes.push(new RegExp(excludesArray[i]));
}
}
return excludes;
}
function generateAnagrams(prefix, postfix, excludes, resultArray) {
if(resultArray.length >= maxCount) return;
if (postfix == "") {
var meetsConditions = true;
if(isValidWord(prefix) === false) meetsConditions = false;
for(var i = 0, n = excludes.length; i < n; i++) {
if(prefix.match(excludes[i]) != null) {
meetsConditions = false;
break;
}
}
if(meetsConditions) {
resultArray.push(prefix);
}
}
for(var i = 0, n = postfix.length; i < n; i++) {
var prefix2 = prefix + postfix.charAt(i);
var postfix2 = postfix.substring(0,i) + postfix.substring(i+1);
generateAnagrams(prefix2, postfix2, excludes, resultArray);
}
}
答案 0 :(得分:0)
1)将isValidWord更改为containsValidWord,并稍微重写逻辑
2)如果您的剩余前缀只包含空格,则匹配