consthydrate=s=>{// get an array with all the numbers in the string, and add the values using reduceconstnumber=s.match(/\d/g).reduce((acc,val)=>acc+parseInt(val),0);return`${number} glass${number!=1?'es':''} of water`;}
We get the following results:
hydrate("1 beer")// 1 glass of water hydrate("2 glasses of wine and 1 shot")// 3 glasses of water hydrate("1 shot, 5 beers, 2 shots, 1 glass of wine, 1 beer")// 10 glasses of water
importredefhydrate(drinks:str)->str:drinkCount=sum(map(int,re.findall("\d+",drinks)))# total number of drinks
# this will also work, drinkCount = sum([int(num) for num in drinks.split(" ") if num.isdigit()])
returnstr(drinkCount)+" glass"+("es"ifdrinkCount>1else"")+" of water"print(hydrate("1 beer"))# output -> 1 glass of water
print(hydrate("2 glasses of wine and 1 shot"))# output -> 3 glasses of water
print(hydrate("1 shot, 5 beers, 2 shots, 1 glass of wine, 1 beer"))# output -> 10 glasses of water
Hey Vidit, I'm happy to hear you wanna suggest a challenge. You can send any suggestions to yo+challenge@dev.to. Feel free to drop the content of your challenge in the email, markdown file works too. Subject doesn't matter too much, we'll know what it is.
funchydrate(_input:String)->String{letnumber=input.split(separator:.init(" ")).map{$0.filter{cinc.isNumber}}.compactMap{Int($0)}.reduce(into:0){$0+=$1}return"\(number) glass\(number>1?"es":"") of water"}hydrate("1 beer")// 1 glass of waterhydrate("2 glasses of wine and 1 shot")// 3 glasses of waterhydrate("1 shot, 5 beers, 2 shots, 1 glass of wine, 1 beer")// 10 glasses of water
functionhydrate(sentence){consthowMany=(sentence.match(/(\d+)/g)||[]).reduce((acc,cur)=>acc+parseInt(cur),0),s=howMany===1?"":"es";return`${howMany} glass${s} of water`;}
Using regular expressions in JavaScript:
We get the following results:
I didn't see yours, but mine is practically identical 😮
Yours has some checks that make it more robust... And that I probably should add to mine 😳
Python solution
I want to suggest a challenge. What should be the subject of my email? Can I send a markdown file?
Hey Vidit, I'm happy to hear you wanna suggest a challenge. You can send any suggestions to yo+challenge@dev.to. Feel free to drop the content of your challenge in the email, markdown file works too. Subject doesn't matter too much, we'll know what it is.
Take care!
Thanks!
My solution in python
Python solution 🐍
My swift solution :
What if I drink "11 beers"?
(I have a feeling I'll be severely under-hydrated)
Your theme looks amazing, what is it?
Any chance you would be willing to upload it for me somewhere? :)