【问题标题】:I'm really stuck on this recursive function question, I need to return the vowel with the greatest count in an object我真的被这个递归函数问题困住了,我需要返回对象中计数最多的元音
【发布时间】:2021-10-17 01:03:00
【问题描述】:
const VOWELS = ['a', 'e', 'i', 'o', 'u'];

const mostFrequentVowel = function (words, counter = {}) {
    let count = 0
    if (words.length === 0) {
        return ''
    }
    let lastString = words[words.length - 1]
    for (let i = 0; i < lastString.length; i++) {
        const letter = lastString[i];
        if (VOWELS.includes(letter)) {
            count++
            if (letter in counter) {
                counter[letter] += 1
            } else {
                counter[letter] = 1
            }
        }
    }
    let values = Object.values(counter)
    let max = Math.max(...values)
    for (let vowel in counter) {
        if (counter[vowel] === max) {
            return vowel
        }
    }
    return mostFrequentVowel(words.slice(0, words.length - 1), counter)

}
console.log(mostFrequentVowel(['dog', 'cow', 'pig', 'chicken', 'horse'])); // 'o'
mostFrequentVowel(['dog', 'cow', 'pig', 'chicken']); // 'i' or 'o'

我无法更新计数器对象以反映最大的元音。我想知道这是否是 for in 循环接近尾声的问题,或者它是否在第一个 for 循环中存在一些逻辑。

【问题讨论】:

  • 为了澄清,你想计算有元音的单词的数量,对吗?不是所有单词中所有元音的数量。
  • 是的,我只需要为第一个返回元音'o',为第二个返回'o'或'i'
  • 如果后者适合您,请考虑简单地使用join 并从所有合并单词的字符串中计算元音。我相信这会通过您当前的演示输入。
  • 如果前一个定义是你想要的,如果每个单词存在多个相同的元音,join 将不起作用。

标签: javascript arrays for-loop object for-in-loop


【解决方案1】:

改用这个:

const VOWELS = ['a', 'e', 'i', 'o', 'u'];

function mostFrequentVowel(inputs)
{
  var max=0;
  VOWELS.forEach(p=>max=Math.max(inputs.join().match(new RegExp(p, 'gm'))?.length ?? 0,max));
  return VOWELS[max]; // <-Update | mistake -> inputs[max];
}

【讨论】:

  • 这太疯狂了,你只是将所有内容压缩成 2 行。我有很多东西要学大声笑
  • @DylanWelzel 注意到我对答案进行了编辑,我忘记声明变量 max。
  • 但在示例中,此代码返回的是 chicken,而不是最常见的元音。 const wordsArray = ['dog', 'cow', 'pig', 'chicken', 'horse'] console.log(mostFrequentVowel(wordsArray))
  • @ManuelMB 没错我会犯错我会编辑答案
【解决方案2】:
'use strict'

const mostFrequentVowel = function (words) {
    if (words.length === 0) {
        return null
    }
    const vowels = ['a', 'e', 'i', 'o', 'u'];
    let vowelsCounter = {
        'a': 0, 
        'e': 0, 
        'i': 0, 
        'o': 0, 
        'u': 0
    };

    const allWords = words.join('')
    console.log(`allWords: ${allWords}`) // allWords: dogcowpigchickenhorse
     
    const chars = allWords.split('');
    console.log(`chars: ${chars}`) // chars: d,o,g,c,o,w,p,i,g,c,h,i,c,k,e,n,h,o,r,s,e
     
    const allVowels = chars.filter(letter => vowels.includes(letter))
    console.log(`allVowels: ${allVowels}`) // allVowels: o,o,i,i,e,o,e

    const vowelsCounterFinal = allVowels.reduce( (acc, vowel) => { // acc ==> acumulator (the previous state) // currentOrder ==> current value in the loop
        acc[vowel] = acc[vowel] + 1
        return acc // REDUCER ==> Remembers the previous state // return the next state 
    },
        vowelsCounter // DEFAULT TO START WITH
    )

    console.log(`vowelsCounterFinal: ${vowelsCounterFinal}`)
 
    const keyWithTheHighestValueFromObject = Object.keys(vowelsCounterFinal).reduce((a, b) => vowelsCounterFinal[a] > vowelsCounterFinal[b] ? a : b);
    // return keyWithTheHighestValueFromObject // return only the vowel
    return { 
        vowel: keyWithTheHighestValueFromObject,
        count: vowelsCounter[keyWithTheHighestValueFromObject] 
    }  // return the vowel and the count
    console.log('Debigging')
}

const wordsArray = ['dog', 'cow', 'pig', 'chicken', 'horse']

console.log(JSON.stringify(mostFrequentVowel(wordsArray), null, 2))

/*
{
  "vowel": "o",
  "count": 3
}
*/

【讨论】:

    【解决方案3】:

    你必须使用递归吗??? 如果没有:

    const VOWELS = ['a', 'e', 'i', 'o', 'u'];
    
    const mostFrequentVowel = function (words) {
        const vowelCount = words.reduce((accumulator, word) => {
            Array.from(word).forEach(character => {
                if (VOWELS.includes(character)) {
                    accumulator = { ...accumulator, [character]: accumulator[character] ? accumulator[character] + 1 : 1 }
                }
            })
            return accumulator
        }, {})
        return Object.keys(vowelCount).reduce((a, b) => vowelCount[a] > vowelCount[b] ? a : b)
    
    }
    console.log(mostFrequentVowel(['dog', 'cow', 'pig', 'chicken', 'horse'])); // 'o'
    console.log(mostFrequentVowel(['dog', 'cow', 'pig', 'chicken'])); // 'i' or 'o'
    

    【讨论】:

      【解决方案4】:

      问题是只有当单词长度=== 1(列表中剩余的最后一个单词)时才应该调用第一个返回。 代码的编写方式,只要有元音,就会调用第一个返回。这个 if 语句可以解决这个问题:

      const mostFrequentVowel = function (words, counter = {}) {
          let count = 0
          if (words.length === 0) {
              return ''
          }
          let lastString = words[words.length - 1]
          for (let i = 0; i < lastString.length; i++) {
              const letter = lastString[i];
              if (VOWELS.includes(letter)) {
                  count++
                  if (letter in counter) {
                      counter[letter] += 1
                  } else {
                      counter[letter] = 1
                  }
              }
          }
      
          if (words.length === 1) {
              let values = Object.values(counter)
              let max = Math.max(...values)
              for (let vowel in counter) {
                  if (counter[vowel] === max) {
                      return vowel
                  }
              }
          }
          else {
              return mostFrequentVowel(words.slice(0, words.length - 1), counter);
          };
      };
      

      希望这个答案对您的问题有所帮助

      【讨论】:

        猜你喜欢
        • 2019-08-25
        • 2022-11-14
        • 2022-01-17
        • 1970-01-01
        • 1970-01-01
        • 2021-08-26
        • 1970-01-01
        • 2019-04-30
        • 1970-01-01
        相关资源
        最近更新 更多