所以,基本上。我想做的是创建一个单词解密器,您可以在其中输入一个打乱的单词并对其进行解密。它工作得很好,尽管我单独检查每个字符,但由于某种原因,额外的字符漏掉了。
我输入“olehl (hello)”
,它将返回“dhole, haole, helio, hello, helos, helot, Holed,holes,holey,hossel,hotel, hovel、hoyle、mohel、sheol、thole、整个”
。我不知道像 "mohel"
和 "dhole"
这样的东西是怎么进去的。
我的代码:
function unscramble(word) {
var words = require("an-array-of-english-words");
var matched = [];
words.forEach((x) => {
if(word.length != x.length) {
} else {
if(matched.length == 42) return;
var newword = word.split('');
var added = 0;
var i = 0;
for(i = 0; i <= newword.length-1; i++) {
if(x.indexOf(newword[i]) >= 0) added++;
if(i == word.length-1 && added == word.length && added == x.length) matched.push(x);
}
}
});
return matched;
}
最佳答案
即使 x 包含 newword
不包含的字符,
x.indexOf(newword[i])
仍然可以为 true。因此 hello
仍然可以匹配 dhole
,因为它们的长度相同,并且 l
匹配两次。如果您只想匹配 hello
而不是像 heloo
(相同字母不同数量)之类的内容,您还需要跟踪消耗了哪些字母。
有很多方法可以做到这一点,但其中一种实际上是从 x
中删除找到的字母。
const idx = x.indexOf(newword[i]);
if (-1 !== idx) {
added++;
// remove this character
// You will have to keep track of the original length of `x` as well
x = x.substring(0, idx) + x.substring(idx + 1, x.length);
}
您还可以对 x
和 newword
进行排序并比较结果字符串/数组。
关于javascript - 额外的角色...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41579663/