Home > database >  How to count 3 different vowels
How to count 3 different vowels

Time:11-01

I want to check if my string has 3 different vowels. Mine code below counts every vowel regardless if they are the same.

function hasThreeVowels(str) {
    let vowelCount = 0;
    let vowels = "aeiou"
    
    for (let char of str) {
        if(vowels.includes(char)) {
            vowelCount  
        }
    }
    return vowelCount >= 3;
}

CodePudding user response:

You could keep track of the vowels you used and only increase the vowelCount if the vowel is not used yet.

function hasThreeDifferentVowels(str) {
  let vowelCount = 0;
  let vowels = 'aeiou';
  let usedVowels = { a: false, e: false, i: false, o: false, u: false };

  for (let char of str) {
    if (vowels.includes(char) && !usedVowels[char]) {
      vowelCount  ;
      usedVowels[char] = true;
    }
  }
  return vowelCount >= 3;
}

console.log(hasThreeDifferentVowels('abaacaaeevaa'));
console.log(hasThreeDifferentVowels('abaacaaeevai'));

CodePudding user response:

Please see the code below:

function hasThreeVowels(str) {
  let vowelCount = 0;
  let vowels = 'aeiou';
  let vowelsObj = {
    a: 0,
    e: 0,
    i: 0,
    o: 0,
    u: 0,
  };

  for (let char of str) {
    if (vowels.includes(char)) {
      if (vowelsObj[char] === 0) {
        vowelsObj[char] = 1;
        vowelCount  ;
      }
    }
  }

  return vowelCount >= 3;
}

To check if a given string to the hasThreeVowels() has three distinct vowels in it, I would create a vowelsObject with keys being each vowel and values 0. Then after looping through each character of the given string, I will check: 1- If the character is vowel or not 2- If yes, I will check if the value of that vowel in the vowelsObject is 0 3- If yes, I will set the value to be one and increase the counter.

CodePudding user response:

You could define the vowels as a Set (of 5). Then subtract each character from that set and if the set's size reduces to just 2, then you know there have been 3 distinct vowels:

function hasThreeVowels(str) {
    const vowels = new Set("aeiou");
    return [...str].some(ch => vowels.delete(ch) && vowels.size < 3);
}

console.log(hasThreeVowels('fantastic')); // false
console.log(hasThreeVowels('amazing')); // false
console.log(hasThreeVowels('fabulous')); // true
console.log(hasThreeVowels('awesome')); // true

I find the use of some elegant, but it will run somewhat faster with a for loop.

  • Related