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;
}
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'));
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.
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
I need to count the occurrence of characters in a given string and print out the unique characters and the number of how many times they appeared. So, for example, if I receive a string of 'HELLO' it should print out:
H: 1,
E: 1,
L: 2,
O: 1
This is a much-simplified version of a problem, but the answer should put me in the right direction. How can I approach this problem?
Thank you in advance.
This is more or less what it should look like in order to make it easier it prints it in JSON you can already convert it to String yourself if you want.
function count_occurrence(text = "") {
const array_from_text = text.split("");
const result = {};
Array.from(new Set(array_from_text)).forEach(word => {
const { length } = array_from_text.filter(w => w === word);
result[word] = length;
});
return result;
};
const occurences = count_occurence("HELLO");
console.log(occurences); // {H: 1, E: 1, L: 2, O: 1}
You could use Array.reduce() to get a count of each occurrence in the input word.
We convert the word to an array using the ... operator, then .reduce() to create an object with a property for each unique letter in the word.
const input = 'HELLO';
const result = [...input].reduce((acc, chr) => {
acc[chr] = (acc[chr] || 0) + 1;
return acc;
}, {});
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
const countChars = (str) => {
const charCount = {} ;
for (const c of [...str]) {
charCount[c] = (charCount[c] || 0) + 1 ;
}
return charCount ;
}
console.log(countChars('HELLO')) ; // {H: 1, E: 1, L: 2, O: 1}
My approach to this problem is:
let str = "HELLO";
// An object for the final result {character:count}
let counts = {};
// Loop through the str...
for (let index = 0; index < str.length; ++index) {
// Get each char
let ch = str.charAt(index);
// Get the count for that char
let count = counts[ch];
// If we have one, store that count plus one;
if (count) {
counts[ch] += 1;
} else {
// if not, store one
counts[ch] = 1;
}
// or more simply with ternary operator
// counts[ch] = count ? count + 1 : 1;.
}
console.log(counts);
Maybe the easiest answer is just split to char and put it into the map.
const count={}
"HELLO".split("").forEach(e=>{
count[e]??=0;
count[e]++;
})
count is what you want.
Use a dictionary like datastructure that gives you O(1) access and update times. In JS you can use an Object literat (not recommended) or a Map.
Iterate over the characters of your string and update the dictionary by incrementing the character count of the current character. If it isn't in your dictionary add it and set the count to one.
When done with the iteration, iterate over the keys of your dictionary, where the values are the the number of occurence of that specific character, and output them in any format of your liking.
const myStr = "Hello"
const myMap = new Map()
for (let c of myStr) {
if (myMap.has(c)) {
myMap.set(c, myMap.get(c)+1)
} else {
myMap.set(c, 1)
}
}
for (let k of myMap.keys()) {
console.log(`${k} occures ${myMap.get(k)} times`)
}
So I want my code to count the amount of times a letter shows up within a string and output the result.
ie:
amount(door, o) ===> 2
Can I do it using a for loop using
function(amount,letter){
var count=0
for (var i=0 ; i < amount.length ; i++) {
if(amount[i] == letter[i]) count++
}
}
not really sure how to make it work
You can split the string into an array, then loop through each of the letters. We have a letterTracker object, which is where our values are stored. If the key of the letter doesn't exist in the object already, we'll add the key to it. If it does exist, we'll just add one to it.
var countLetters = (string)=>{
const stringArr = string.split('')
let letterTracker = {};
stringArr.forEach(letter=>{
letterTracker[letter]
? letterTracker[letter]++
: letterTracker[letter] = 1
});
return letterTracker;
}
countLetters('wuddup'); //returns { w: 1, u: 2, d: 2, p: 1 }
Using a more ES5 friendly method, and without splitting the string into an array, we can do this (the same result will be achieved):
function countLetters(string){
let letterTracker = {};
for(let i = 0; i < string.length; i++){
if(letterTracker[string[i]]){
letterTracker[string[i]]++
} else {
letterTracker[string[i]] = 1
}
}
return letterTracker;
}
countLetters('wuddupp?'); //returns { w: 1, u: 2, d: 2, p: 2, ?: 1 }
Your code was almost correct but there some mistakes
You have to give the function a name
You have to return count
You have to pass actual strings
You should use let or const instead of var
You should use === instead of ==
function amount(word, letter) {
let count = 0;
for (let i = 0; i < word.length; i++) {
if(word[i] === letter) count++
}
return count;
}
console.log(amount('door', 'o'));
Using array methods you can simplify even more
function amount(word, letter) {
return Array.prototype.reduce.call(word, (acc, el) => acc + (el === letter), 0);
}
console.log(amount('door', 'o'));
What is the best way to count each vowel separately in a string and display it as "A=0", "i=2", "e=1", and so on, case insensitively? I have this so far, but it doesn't count each symbol, only the total amount.
let arr_vowels = 'aeiouAEIOU'.split('');
let count = 0;
word.split('').forEach(function(e) {
if (arr_vowels.indexOf(e) !== -1) {
count++;
}
});
console.log(count);
With the current approach, you are increasing the same count for a vowel.
One approach can be using a Map for example counting each vowel separately, and then loop the entries of the Map to get the key and value.
const vowels = 'aeiouAEIOU';
const str = "This is A test for counting vowels.";
const m = new Map();
for (let i = 0; i < str.length; i++) {
let char = str[i]
if (vowels.includes(char)) {
!m.has(char) ? m.set(char, 1) : m.set(char, m.get(char) + 1);
}
}
for (const [key, value] of m.entries()) {
console.log(`${key} = ${value}`);
}
Similar to the other solution, but simply with an object, you can do the following:
const vowels = {
a: 0,
e: 0,
i: 0,
o: 0,
u: 0,
};
const str = "This is A test for counting vowels.";
str.split('').forEach((letter) => {
const insensitiveLetter = letter.toLowerCase();
if (vowels[insensitiveLetter] !== undefined) {
vowels[insensitiveLetter] += 1;
}
});
I came across a problem that seemed very straightforward, but as I coded more some of my expected return were not as I expected.
Any help is appreciated. If you do provide any help please explain your approach and how I got stuck.
The problem:
We're given a string and need to see if it can be broken down into words from a dictionary array. For example:
const str = "applecomputer";
const dictArr = ["apple", "computer"];
stringBreakdown(str, dictArr);
// true
Assuming that there are no repeats in the dictionary array, can you write a method that will return true if the string can be broken down into words from the array, or false if not?
The two test cases:
Expect stringBreakdown('crazyrichasians', [ 'crazy', 'rich', 'asians' ]) // to return true
Expect stringBreakdown('lockcombination', [ 'lock', 'combo' ]) // to return false
My code and approach:
Create a hash map of all the characters in the string
Create a helper function remove charters from each string in the array
As I remove the character in the string I will also decrease each time I've seen that letter from the hash map
If I seen all the letters in that string then I will remove it from the given array
Lastly, if the given array length is less than 0, return true because I was able to make all of the word or turn false because more words are in the array
const stringBreakdown = (str, dictArr)=> {
let hashDictionary = {};
let shouldRemoveWord
for(let x = 0; x <= str.length-1;x++){
!hashDictionary[str[x]] ? hashDictionary[str[x]] =1 : hashDictionary[str[x]]+=1
}
for(let y = 0; y < dictArr.length;y++ ){
shouldRemoveWord = removeLetters(hashDictionary,dictArr[y])
if(shouldRemoveWord === true){
dictArr.splice(y,1)
}
}
console.log('dictArr',dictArr)
return dictArr.length > 0 ? true : false;
}
const removeLetters = (hash,word) =>{
let modifiedWord = word.split('')
for(let k = 0; k < modifiedWord.length;k++){
if(hash[word[k]]){
modifiedWord.splice(k,1)
hash[word[k]]-=1
}
}
return modifiedWord.join('').length < 0 ? true : false;
}
You can go over each word provided in the array then:
Firstly, check if the length of all the words combined together matches with the length of the string under test. If not return false.
Secondly, if the length matches, then check whether every word as a whole is included as a sub-string in the supplied string:
function stringBreakdown(str, dictArr){
return dictArr.join("").length === str.length
&&
dictArr.every(word => str.includes(word));
}
//tests
console.log(stringBreakdown('crazyrichasians', [ 'crazy', 'rich', 'asians' ]));
console.log(stringBreakdown('lockcombination', [ 'lock', 'combo' ]));
console.log(stringBreakdown('applecomputer', [ 'apple', 'computer']));
console.log(stringBreakdown('appelcomputer', [ 'apple', 'computer']));
console.log(stringBreakdown('appcolemputer', [ 'apple', 'computer']));
console.log(stringBreakdown('applecomputer', [ 'app', 'le', 'computer']));
Your approach is dubious as when you go through each character by character you are not looking at the word it forms i.e. in your case if applecomputer is the string and the array has ['appel', 'comterpu'] your algorithm will return true in this case.
It is because you are making a character map from the inout string str and then going through each word's character and decrementing the occurrence of it in the character map so the combination doesn't matter.
const stringBreakdown = (str, dictArr)=> {
let hashDictionary = {};
let shouldRemoveWord
for(let x = 0; x <= str.length-1;x++){
!hashDictionary[str[x]] ? hashDictionary[str[x]] =1 : hashDictionary[str[x]]+=1
}
for(let y = 0; y < dictArr.length;y++ ){
shouldRemoveWord = removeLetters(hashDictionary,dictArr[y])
if(shouldRemoveWord === true){
dictArr.splice(y,1)
}
}
return dictArr.length > 0 ? true : false;
}
const removeLetters = (hash,word) =>{
let modifiedWord = word.split('')
for(let k = 0; k < modifiedWord.length;k++){
if(hash[word[k]]){
modifiedWord.splice(k,1)
hash[word[k]]-=1
}
}
return modifiedWord.join('').length < 0 ? true : false;
}
//doesn't work outputs true
console.log(stringBreakdown('applecomputer', ['appel', 'computer']));
simply loop through the dictionary
const dictArr = ["lock", "combo"];
function checkInDic(val){
var len = 0;
dictArr.forEach(element => {
if(val.includes(element)){
len += element.length;
}else{
return false;
}
});
if(len == val.length){
return true;
}else{
return false;
}
}
I'm using basic JavaScript to count the number of vowels in a string. The below code works but I would like to have it cleaned up a bit. Would using .includes() help at all considering it is a string? I would like to use something like string.includes("a", "e", "i", "o", "u") if at all possible to clean up the conditional statement. Also, is it needed to convert the input into a string?
function getVowels(str) {
var vowelsCount = 0;
//turn the input into a string
var string = str.toString();
//loop through the string
for (var i = 0; i <= string.length - 1; i++) {
//if a vowel, add to vowel count
if (string.charAt(i) == "a" || string.charAt(i) == "e" || string.charAt(i) == "i" || string.charAt(i) == "o" || string.charAt(i) == "u") {
vowelsCount += 1;
}
}
return vowelsCount;
}
You can actually do this with a small regex:
function getVowels(str) {
var m = str.match(/[aeiou]/gi);
return m === null ? 0 : m.length;
}
This just matches against the regex (g makes it search the whole string, i makes it case-insensitive) and returns the number of matches. We check for null incase there are no matches (ie no vowels), and return 0 in that case.
Convert the string to an array using the Array.from() method, then use the Array.prototype.filter() method to filter the array to contain only vowels, and then the length property will contain the number of vowels.
const countVowels = str => Array.from(str)
.filter(letter => 'aeiou'.includes(letter)).length;
console.log(countVowels('abcdefghijklmnopqrstuvwxyz')); // 5
console.log(countVowels('test')); // 1
console.log(countVowels('ddd')); // 0
function countVowels(subject) {
return subject.match(/[aeiou]/gi).length;
}
You don't need to convert anything, Javascript's error handling is enough to hint you on such a simple function if it will be needed.
Short and ES6, you can use the function count(str);
const count = str => (str.match(/[aeiou]/gi) || []).length;
This could also be solved using .replace() method by replacing anything that isn't a vowel with an empty string (basically it will delete those characters) and returning the new string length:
function vowelCount(str) {
return str.replace(/[^aeiou]/gi, "").length;
};
or if you prefer ES6
const vowelCount = (str) => ( str.replace(/[^aeiou]/gi,"").length )
You can convert the given string into an array using the spread operator, and then you can filter() the characters to only those which are vowels (case-insensitive).
Afterwards, you can check the length of the array to obtain the total number of vowels in the string:
const vowel_count = string => [...string].filter(c => 'aeiou'.includes(c.toLowerCase())).length;
console.log(vowel_count('aaaa')); // 4
console.log(vowel_count('AAAA')); // 4
console.log(vowel_count('foo BAR baz QUX')); // 5
console.log(vowel_count('Hello, world!')); // 3
You can use the simple includes function, which returns true if the given array contains the given character, and false if not.
Note: The includes() method is case sensitive. So before comparing a character convert it to lowercase to avoid missing all the possible cases.
for (var i = 0; i <= string.length - 1; i++) {
if ('aeiou'.includes(string[i].toLowerCase())) {
vowelsCount += 1;
}
}
Use this function to get the count of vowels within a string. Works pretty well.
function getVowelsCount(str)
{
//splits the vowels string into an array => ['a','e','i','o','u','A'...]
let arr_vowel_list = 'aeiouAEIOU'.split('');
let count = 0;
/*for each of the elements of the splitted string(i.e. str), the vowels list would check
for any occurence and increments the count, if present*/
str.split('').forEach(function(e){
if(arr_vowel_list.indexOf(e) !== -1){
count++;} });
//and now log this count
console.log(count);}
//Function Call
getVowelsCount("World Of Programming");
Output for the given string would be 5. Try this out.
//Code -
function getVowelsCount(str)
{
let arr_vowel_list = 'aeiouAEIOU'.split('');
let count = 0;
str.split('').forEach(function(e){
if(arr_vowel_list.indexOf(e) !== -1){
count++;} });
console.log(count);
}
Use match but be careful as it can return a null if no match is found. This solves it:
const countVowels = (subject => (subject.match(/[aeiou]/gi) || []).length);
function vowels(str) {
let count=0;
const checker=['a','e','i','o','u'];
for (let char of str.toLowerCase){
if (checker.includes(char)) {
count++;
}
return count;
}
function vowels(str) {
const match = str.match(/[aeiou]/gi);
return match ? match.length : 0 ;
}
count = function(a) {
//var a=document.getElementById("t");
console.log(a); //to see input string on console
n = a.length;
console.log(n); //calculated length of string
var c = 0;
for (i = 0; i < n; i++) {
if ((a[i] == "a") || (a[i] == "e") || (a[i] == "i") || (a[i] == "o") || (a[i] == "u")) {
console.log(a[i]); //just to verify
c += 1;
}
}
document.getElementById("p").innerText = c;
}
<p>count of vowels </p>
<p id="p"></p>
<input id="t" />
<input type="button" value="count" onclick="count(t.value)" />
This is the shortest solution
function getCount(str) {
return (str.match(/[aeiou]/ig)||[]).length;
}
const containVowels = str => {
const helper = ['a', 'e', 'i', 'o', 'u'];
const hash = {};
for (let c of str) {
if (helper.indexOf(c) !== -1) {
if (hash[c]) {
hash[c]++;
} else {
hash[c] = 1;
}
}
}
let count = 0;
for (let k in hash) {
count += hash[k];
}
return count;
};
console.log(containVowels('aaaa'));
As the introduction of forEach in ES5 this could be achieved in a functional approach, in a more compact way, and also have the count for each vowel and store that count in an Object.
function vowelCount(str){
let splitString=str.split('');
let obj={};
let vowels="aeiou";
splitString.forEach((letter)=>{
if(vowels.indexOf(letter.toLowerCase())!==-1){
if(letter in obj){
obj[letter]++;
}else{
obj[letter]=1;
}
}
});
return obj;
}
My solution:
const str = "In West Philadephia, born and raised.";
const words = str.split("");
function getVowelCount() {
return words.filter(word => word.match(/[aeiou]/gi)).length;
}
console.log(getVowelCount());
Output: 12
You can easily solve this using simple regex. match() method matches string agains a regex variable. return an array if the is a matches and return null if no match is found.
function getVowels(str) {
let vowelsCount = 0;
const regex = /[aiueo]/gi;
vowelsCount = str.match(regex);
return vowelsCount ? vowelsCount.length : 0;
}
console.log(getVowels('Hello World')) => return 3
console.log(getVoewls('bbbcccddd') => return 0
Just use this function [for ES5] :
function countVowels(str){
return (str.match(/[aeiou]/gi) == null) ? 0 : str.match(/[aeiou]/gi).length;
}
Will work like a charm
(A)
const countVowels = data => [...data.toLowerCase()].filter(char => 'aeiou'.includes(char)).length;
(B)
const countVowels = data => data.toLowerCase().split('').filter(char => 'aeiou'.includes(char)).length;
countVowels("Stackoverflow") // 4
The following works and is short:
function countVowels(str) {
return ( str = str.match(/[aeiou]/gi)) ? str.length : 0;
}
console.log(countVowels("abracadabra")); // 5
console.log(countVowels("")); // 0
One more method (using reduce):
function getVowels(str) {
return Array.from(str).reduce((count, letter) => count + 'aeiou'.includes(letter), 0);
}
Here is the my solution for the problem:
function getVowelsCount(s) {
let vowels = ["a", "e", "i", "o", "u"];
let count=0;
for(let v of s) {
if(vowels.includes(v)){
console.log(v);
count=count+1;
}
}
console.log(count);
}
After research and without using regex, this is what I found the simplest to understand for new devs like me.
function vowelCount (string) {
let vowel = "aeiouy"; // can also be array
let result = 0;
for (let i = 0; i < string.length; i++) {
if (vowel.includes(string[i].toLowerCase())) {
result++;
}
}
return result;
}
console.log(vowelCount("cAkeYE"));
function vowelCount(str){
str=str.toLowerCase()
let count=[]
for(let i=0;i<str.length;i++){
if(str.charAt(i)=='u'||str.charAt(i)=='o'||str.charAt(i)=='i'||str.charAt(i)=='e'||str.charAt(i)=='a'){
count.push(str.charAt(i))//to store all the vowels in an array
}
}
let eachcount={}
count.forEach((x)=>eachcount[x]?eachcount[x]++:eachcount[x]=1) //to count each vowel from the count array
return eachcount
}
console.log(vowelCount("hello how Are You"))
function vowelsCount(sentence) {
let vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
let count = 0;
let letters = Array.from(sentence);
letters.forEach(function (value) {
if (vowels.includes(value)) {
count++
}
})
return count;
}
console.log(vowelsCount("StackOverFlow"));
Another solution using Set to lookup characters in constant time and reduce() to do the actual counting. The implementation also uses the spread syntax for string as strings are Iterable.
/**
* Count vowels in a string. Ignores case.
* #param {string} str String to count the vowels in
* #returns numbers of vowels
*/
function countVowels(str) {
let vowels = new Set("aeiou")
return [...str.toLowerCase()].reduce((count, character) => count + vowels.has(character) || 0, 0)
};
console.log(countVowels("apple"))
console.log(countVowels("pears are yummy"))
.as-console-wrapper { max-height: 100% !important; top: 0; }