7/15/20 problems Hashes Flashcards
1
Q
Write a method frequent_letters that takes in a string and returns an array containing the characters that appeared more than twice in the string.
A
def frequent_letters(string) freq_hash = Hash.new(0)
freq_letters = []
alphabet = (“a”..”z”)
string.each_char do |char| if alphabet.include?(char) freq_hash[char] += 1 end end
freq_hash.each do |k, v| if v > 2 freq_letters << k end end return freq_letters # return freq_hash end
p frequent_letters('mississippi is best!!!!!') #=> ["i", "s"] p frequent_letters('bootcamp') #=> []
2
Q
anagram returns boolean representing whether the letters in word1 can be rearranged to form word2
A
def anagram?(word1, word2) #do each word contain the same amount of each letter hash1 = Hash.new(0) hash2 = Hash.new(0)
alphabet = (“a”..”z”)
word1.each_char do |char| if alphabet.include?(char) hash1[char] += 1 end end word2.each_char do |char| if alphabet.include?(char) hash2[char] += 1 end end
if hash1 == hash2
#comparing keys is most common
end
p anagram?(“teacher”, “cheater”) # => true
p anagram?(“desert”, “dessert”) # => false
3
Q
takes integer and converts to roman numeral string
A
def int_to_roman(num) roman_hash = { "M" => 1000, "CM" => 900, "D" => 500, "CD" => 400, "C" => 100, "XC" => 90, "L" => 50, "XL" => 40, "X" => 10, "IX" => 9, "V" => 5, "IV" => 4, "I" => 1 } end puts int_to_roman(5) #=> "V" puts int_to_roman(1764) #=> "MDCCLXIV" puts int_to_roman(999) #=> "CMXCIX"