-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckIfSameAmountofLetters.rb
More file actions
executable file
·83 lines (57 loc) · 2.05 KB
/
CheckIfSameAmountofLetters.rb
File metadata and controls
executable file
·83 lines (57 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# 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.
def validate_word(word)
split_string = word.downcase.split("")
letter_present = Hash.new(0)
split_string.each {|letter| letter_present[letter] += 1}
letter_present.values.each_with_index do |count, i |
if i == (letter_present.length-1)
return true
elsif letter_present.values[i] != letter_present.values[i+1]
return false
end
end
end
puts validate_word("abcabc")
puts "should return true"
puts validate_word("Abcabc")
puts "should return true"
puts validate_word("AbcabcC")
puts "should return false"
puts validate_word("AbcCBa")
puts "should return true"
puts validate_word("pippi")
puts "should return false"
puts validate_word("?!?!?!")
puts "should return true"
puts validate_word("abc123")
puts "should return true"
puts validate_word("abcabcd")
puts "should return false"
puts validate_word("abc!abc!")
puts "should return true"
puts validate_word("abc:abc")
puts "should return false"
#best method is this:
#i wish i knew about the .count() method! Ruby makes things so easy, I'm still living in C syntax days.
def validate_word(word)
count = 0
s = word.downcase
s.each_char do |c|
if count == 0
count = s.count(c)
elsif count != s.count(c)
return false
end
end
true
end