算法挑战:模糊搜索
我最近参加了一项算法挑战,使用以下条件创建模糊搜索:
给定一个集合数组,创建一个函数,该函数接收一个参数并返回一个仅包含以以下任一开头的值的新数组:
A)提供的参数 B) 提供了参数,但有 1 个差异(即 1 个不正确的字母)
数组为:fruits = [apple, apricot,banana,pear,mango,cherry,tomato]
所以:
- fuzzySearch('ap') = ['apple, apricot ']
- fuzzySearch('app') = ['苹果', '杏']
- fuzzySearch('appl') = ['苹果']
- fuzzySearch('pa') = ['banana', 'mango']
这是我想出的解决方案:
const fruits = ['apple', 'apricot', 'banana', 'pear', 'mango', 'cherry', 'tomato']
function fuzzySearch(str) {
return fruits.filter(fruit =>
{
let letterCount = 0
const fruitLetArr = fruit.toLowerCase().split('')
const strArr = str.toLowerCase().split('')
for (var i = 0; i < strArr.length; i++) {
console.log(fruitLetArr[i], strArr[i], i, letterCount)
if (fruitLetArr[i] !== strArr[i]) letterCount++
if (letterCount === 2) break;
}
if (letterCount < 2) return true
});
}
fuzzySearch(str)
有人能想到一种更快的方法,在找到解决方案之前不需要迭代每个值吗?
I recently took part in an algorithm challenge to create a Fuzzy search with the following criteria:
Given a set array, create a function that receives one argument and returns a new array containing only the values that start with either:
A) The argument provided
B) The argument provided but with 1 difference (i.e. 1 incorrect letter)
The array was: fruits = [apple, apricot, banana, pear, mango, cherry, tomato]
so:
- fuzzySearch('ap') = ['apple, apricot']
- fuzzySearch('app') = ['apple', 'apricot']
- fuzzySearch('appl') = ['apple']
- fuzzySearch('pa') = ['banana', 'mango']
This is the solution I came up with:
const fruits = ['apple', 'apricot', 'banana', 'pear', 'mango', 'cherry', 'tomato']
function fuzzySearch(str) {
return fruits.filter(fruit =>
{
let letterCount = 0
const fruitLetArr = fruit.toLowerCase().split('')
const strArr = str.toLowerCase().split('')
for (var i = 0; i < strArr.length; i++) {
console.log(fruitLetArr[i], strArr[i], i, letterCount)
if (fruitLetArr[i] !== strArr[i]) letterCount++
if (letterCount === 2) break;
}
if (letterCount < 2) return true
});
}
fuzzySearch(str)
Can anyone think of a faster way that doesn't involve iterating over every value before a soltion can be found?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是应该稍微更有效率的东西。也更容易阅读。在此解决方案中,我假设“差异”是指用一个字母替换另一个字母,而不是添加另一个字母。
轻微更新。实际上没有必要切片水果。我们可以循环输入字符串:
Here's something that should be slightly more efficient. Also easier to read. In this solution, I am assuming that by "difference" you mean a substitution of a letter for another letter, rather than the addition of another letter.
Slight update. Slicing the fruit is not actually necessary. We can just loop through the input string: