javascript - 额外的角色...?

标签 javascript arrays node.js

所以,基本上。我想做的是创建一个单词解密器,您可以在其中输入一个打乱的单词并对其进行解密。它工作得很好,尽管我单独检查每个字符,但由于某种原因,额外的字符漏掉了。

我输入“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); 
}

您还可以对 xnewword 进行排序并比较结果字符串/数组。

关于javascript - 额外的角色...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41579663/

相关文章:

node.js - 如何使用node.js添加不压缩的zip文件?

javascript - 如何使用聚合来包含未从该方法返回的文档?

javascript - 如何在javascript对象中查找动态键的值

javascript - 我应该在 service worker 中使用 self 还是 this ?

javascript - Sencha touch 2 azure如何向invokeApi添加 header 身份验证?

c++ - 如何从(嵌套的)std::initializer_list 确定大小?

c# - 如何在不使用循环的情况下修剪字符串数组中的每个字符串元素?

javascript - float 数组的音调检测

node.js - AngularJS 和 NodeJS 中的 View 模板引擎在概念上有什么区别?

javascript - 如何将数组正确转换为 json_encode