I have problem with one loop exercise. I have written 3 possible answers and my code failed each time. My counter failed, and I have a problem with the scope of variables and nested loops.
I have an array of food, and I have to find the one food with the best vowels to length ratio and print it to the console. First I tried creating 3 variables two to compare with each other and one to store the result in it, and that gave me undefined for parts of the array. I expected that food3 would have all the iteration of i, but it had only i[2], and food2 had i[1], i[undefined], i[3].
In my second try had 2 variables, but my counter failed.
const getGets = (arr) => {
let index = 0;
return () => {
const toReturn = arr[index];
index += 1;
return toReturn;
};
};
// Test input
const testInput = [
'4', 'pizza', 'macaroni', 'kiufte', 'banica'
];
const gets = this.gets || getGets(testInput);
const n = +gets();
let vowels
let food = '';
let ratio
let counter = 0;
for (let i = 1; i <= n; i++) {
let food1 = gets(); // pizza, undefined, kiufte, undefined
let food2 = gets();
let vowels1 = 0
let vowels2 = 0
let ratio1 = 0
let ratio2 = 0
for (let element of food1) {
console.log(element) // failed here, because of food1
if (element === 'a' || element === 'o' || element === 'u' || element === 'e' || element === 'i') {
counter++;
continue;
}
}
vowels1 = vowels1 + counter;
retio1 = vowels1 / food1.length;
retio2 = vowels2 / food2.length;
if (ratio1 >= ratio2) {
ratio1 = ratio
ratio2 = ratio1
food1 = food
food2 = food1
vowels1 = vowels
vowels2 = vowels1
}
console.log(`${food} ${vowels}/${food.length}`)
couner = 0;
}
My answer creates an object to store the results. Then it loops through the passed array and uses a regular expression to check for the number of vowels. Then it checks to see if the vowels variable is valid and returns the number of vowels if not returns 0, then is divides that by the word length.
After that the result object is checked to see if the word's ratio is greater than one that is already stored. If the new ratio is better, it is stored.
const testInput = [
'4', 'pizza', 'macaroni', 'kiufte', 'banica'
];
function compareRatios(input) {
let result = {"word" : "","ratio" : 0,"vowels" : 0};
input.forEach((word) =>{
let vowels = word.match(/[aeiou]/gi);
ratio = ((vowels) ? vowels.length : 0) / word.length
if(result.ratio < ratio)
result = {"word" : word,"ratio" : ratio,"vowels" : vowels.length};
});
console.log(`${result.word} ${result.ratio} ${result.vowels}`)
}
compareRatios(testInput)