CodeWars instead of morning coffee

Today I’ve decided to take over control of my brain… finally. What that does mean? It means that my pareocerebellum (mózg gadzi, móżdżek) won’t control my body anymore (when its not necessary of course) so what thats does mean? That means, that I will defy (przeciwstawiać się) my basic instincts instead to focus on neocortex (kora nowa).
So every morning I’ll focus on at least one codewars assignment , and will publish task, solution and best solution (this is only for learning purpose, so spoiler alert for those, who want solve codewars tasks).
The quote of the day (or even year: „Don`t let your brain (pareocelebellum) control your body!”
Description:
Given an array (arr) as an argument complete the function countSmileys
that should return the total number of smiling faces.
Rules for a smiling face:
-Each smiley face must contain a valid pair of eyes. Eyes can be marked as :
or ;
-A smiley face can have a nose but it does not have to. Valid characters for a nose are -
or ~
-Every smiling face must have a smiling mouth that should be marked with either)
or D
.
No additional characters are allowed except for those mentioned.
Valid smiley face examples:
:) :D ;-D :~)
Invalid smiley faces:
;( :> :} :]
Example cases:
countSmileys([':)', ';(', ';}', ':-D']); // should return 2;
countSmileys([';D', ':-(', ':-)', ';~)']); // should return 3;
countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;
Note: In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same
————– my solution:
def count_smileys(arr) return 0 if arr.empty? valid_face = /[:;][-~]?[\)D]/i arr.select! { |elem| elem =~ valid_face } arr.count end
and the:
————– best:
def count_smileys(arr)
arr.count { |e| e =~ /(:|;){1}(-|~)?(\)|D)/ }
end
def count_smileys(arr)
arr.count { |e| e =~ /[:;]{1}[-~]?[)D]/ }
end
def count_smileys(arr)
result = []
arr.each do |c|
if c.start_with?(":", ";") && c.end_with?(")", "D")
result << c unless c.include?(' ')
end
end
result.size
end
Najnowsze komentarze