如何使用JavaScript查找句子中包含的每个单词的字谜


E.g.:
'abba' and 'baab' are equal
'abba' and 'bbaa' are equal
'abba' and 'abbba' are NOT equal
'abba' and 'abca' are NOT equal

你必须写一个函数来找到一个句子中包含的每个单词的所有字谜(注意:句子中的单词之间仅用空格分隔)

你将得到两个输入:一个句子和一个单词数组。你必须返回一个包含所有字谜的数组,如果没有字谜则返回一个空数组。

注意:

  • 您的解决方案将被自动测试;确保提供运行代码
  • 不要专注于创建任何视觉效果,只是JavaScript
  • 如果您的代码挂起或运行时间过长,您的解决方案将不会被评估
  • 您可以自由创建其他函数,但要保留solution作为主要函数
/* your code here */
const sort = (word) => word.split('').sort().join('');
function anagrams(word, words) {
let token = sort(word);
return words.filter((w) => sort(w) === token);
}
console.log(anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']));

}
// test your solution
solution('dvvd  pddp', ['ddvv', 'dvcd', 'vvdd', 'pdpd'])
// ['ddvv', 'vvdd', 'pddp']
solution('laser space', ['lazing', 'lazy', 'lacer'])
// []
solution('We will eat tenderising meat at Rivera with no regally plate because there is none',
['administration', 'ingredients', 'admit', 'beat', 'arrive', 'blood', 'door', 'each', 'on', 'economic', 'gallery', 'edge', 'three', 'drop'])
// ['ingredients', 'arrive', 'on', 'gallery', 'three'] ```

我应该如何测试我的解决方案?

编写一个函数,对单词(小写)的字母进行排序,并返回排序后的变位图。

使用该函数从输入短语中创建所有排序的单词,并将其转换为集合。

最后,迭代anagrams数组,对于每个单词,看看它的排序版本是否在集合中。如果是,它应该在结果中。

我应该如何测试我的解决方案?

使用代码挑战中给出的输入/输出示例。

使用这些输入运行solution函数,并验证返回值是否符合预期。看看下面是怎么做的:

function solution(phrase, anagrams) {
const sortWord = word => [...word.toLowerCase()].sort().join("");
let words = new Set(phrase.match(/S+/g).map(sortWord));
return anagrams.filter(anagram => words.has(sortWord(anagram)));
}
// tests
const tests = [
{ input: ['dvvd  pddp', ['ddvv', 'dvcd', 'vvdd', 'pdpd']],
expected: ['ddvv', 'vvdd', 'pdpd'] },
{ input: ['laser space', ['lazing', 'lazy', 'lacer']],
expected: [] },
{ input: ['We will eat tenderising meat at Rivera with no regally plate because there is none', ['administration', 'ingredients', 'admit', 'beat', 'arrive', 'blood', 'door', 'each', 'on', 'economic', 'gallery', 'edge', 'three', 'drop']],
expected: ['ingredients', 'arrive', 'on', 'gallery', 'three'] }
];
for (let { input, expected } of tests) {
let output = solution(...input);
if (JSON.stringify(output) !== JSON.stringify(expected)) {
throw "got " + JSON.stringify(output) + ", but expected " + JSON.stringify(expected);
}
}
console.log("all tests passed");

最新更新