如何在单词数组中按长度找到最接近的单词?

问题描述 投票:0回答:1
/**
 * @param {string} str1 - the first string to compare
 * @param {string} str2 - the second string to compare
 * @returns {number} the absolute difference in length between `str1` and `str2`
 */
const getDistanceByLength = (str1, str2) => {
  return Math.abs(str1.length-str2.length);
};

/**
 * @param {string} word - the original string
 * @param {string[]} words - an array of strings
 * @param {(str1: string, str2: string) => number} - a function that
 *  takes two strings and returns a number representing the distance between them
 * @param {number} threshold - the maximum distance that is still considered "close"
 * @returns {string} the string in `words` with the minimum distance to `word`
 *  as calculated by `distanceFn`, unless that distance is strictly greater than
 *  the `threshold`, in which case the original `word` is returned.
 */
const getClosestWord = (word, words, getDistanceByLength, threshold) => {
  for(i=0;i<words.length;i++){
    if(getDistanceByLength(word,words[i]) <= threshold){
      return words[i];
    }
  }
  return word;

};

我遇到的问题是我无法弄清楚

getClosestWord()
中循环遍历数组并得出最短距离(从
getDistanceByLength
开始)所需的逻辑。如果距离大于
word
,它还会返回第一个
threshold
。现在,一旦遇到通过条件的单词,它就会停止循环,而不是遍历整个数组,然后选择距离最短的
words[i]

word
只是函数中传递的随机单词。我正在使用的
words
数组:

words: ["bed", "bank", "fence", "bridges"] 

如果有任何居高临下的情况,请告诉我,或者如果你们都需要更多信息。

javascript arrays string function for-loop
1个回答
0
投票

要查找数组中距离最短且小于阈值的单词,您需要:

  • 检查数组中的所有单词(这意味着您不能在数组中
    return
  • 确认当前单词的距离小于阈值距离
  • 确认当前单词的距离小于之前看到的最近单词的距离。

要删除循环中间的

return
,您应该跟踪到目前为止您所看到的最接近的单词。下面我将这个单词存储在一个名为
closestWord
的变量中,以便您可以在循环完成后返回它(循环完成后,您已经查看了所有单词,因此您可以放心地说最接近的单词是在
closestWord
)。您可以存储的另一件事(但不是强制执行)是计算出的
closestWord
距离。下面我将其存储在
closestDist
中。这使您可以确认为当前单词计算的距离小于(或等于,如果您想获取所看到的最后一个最近距离单词)迄今为止所看到的最近单词距离。从技术上讲,我们可以删除
closestDist
,因为它可以通过调用
getDistanceByLength
并传入
closestWord
word
来计算,但这允许我们将其初始化为
Infinity
,使循环内的比较逻辑更容易,如下所示当你第一次遇到小于阈值的单词时,不需要特殊情况:

const getDistanceByLength = (str1, str2) => Math.abs(str1.length - str2.length);

const getClosestWord = (word, words, distanceFn, threshold) => {
  let closestWord = word;
  let closestDist = Infinity;
  for (let i = 0; i < words.length; i++) {
    const currDist = distanceFn(word, words[i]);
    // If the current word's distance is less than the threshold
    // and its distance is less than the distance for the closest word seen so far
    if (currDist <= threshold && currDist <= closestDist) {
      closestWord = words[i];
      closestDist = currDist;
    }
  }
  return closestWord;
};

console.log(getClosestWord(
  "mouse", ["fish", "cat", "dog", "bird", "ant", "ox", "squid"],
  getDistanceByLength,
  4
));

© www.soinside.com 2019 - 2024. All rights reserved.