Created
March 20, 2016 19:19
-
-
Save pinkopaque22/9720adac16cf87d9036e to your computer and use it in GitHub Desktop.
Codewars Solution to Character Counter in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CHARACTER COUNTER | |
You are going to be given a word. Your job will be to make sure that each character in that word has the exact same number of occurrences. You will return true if it is valid, or false if it is not. | |
For example: | |
"abcabc" is a valid word because 'a' appears twice, 'b' appears twice, and'c'appears twice. | |
"abcabcd" is NOT a valid word because 'a' appears twice, 'b' appears twice,'c' appears twice, but 'd' only appears once! | |
"123abc!" is a valid word because all of the characters only appear once in the word. | |
For this kata, capitals are considered the same as lowercase letters. Therefore: 'A' == 'a' . | |
INPUT | |
A string (no spaces) containing [a-z],[A-Z],[0-9] and common symbols. The length will be 0 < string < 100. | |
OUTPUT | |
true if the word is a valid word, or false if the word is not valid. | |
Test Cases | |
1.) Test.assert_equals(validate_word("abcabc"),True) | |
2.) Test.assert_equals(validate_word("Abcabc"),True) | |
3.) Test.assert_equals(validate_word("AbcabcC"),False) | |
4.) Test.assert_equals(validate_word("AbcCBa"),True) | |
5.) Test.assert_equals(validate_word("pippi"),False) | |
6.) Test.assert_equals(validate_word("?!?!?!"),True) | |
7.) Test.assert_equals(validate_word("abc123"),True) | |
8.) Test.assert_equals(validate_word("abcabcd"),False) | |
9.) Test.assert_equals(validate_word("abc!abc!"),True) | |
10.) Test.assert_equals(validate_word("abc:abc"),False) | |
////////CODE/////////// | |
def validate_word(word) | |
char_counter = {} | |
word.split('').each do |char| #chained method to pull each element out of string | |
char.downcase! | |
if char_counter.keys.include? char | |
char_counter[char] = char_counter[char] + 1 #assigning an existing key in hash | |
else | |
char_counter[char] = 1 #create new key in hash | |
end | |
end | |
puts char_counter.inspect | |
vals = char_counter.values | |
vals.each_with_index do |num, i| | |
if i < vals.size-1 # can use .size or .count | |
if num != vals[i + 1] #or use unelss | |
puts "FFFF#{num}" | |
puts "SSSS#{vals.size}" | |
return false | |
end | |
end | |
end | |
return true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment