# Write a method that takes in a string. Your method should return the
# most common letter in the array, and a count of how many times it
# appears.
#
# Difficulty: medium.
def most_common_letter(string)
letter = 0
letter_count = 0
idx1 = 0
mostfreq_letter = 0
largest_letter_count = 0
while idx1 < string.length
letter = string[idx1]
idx2 = 0
while idx2 < string.length
if letter == string[idx2]
letter_count += 1
end
idx2 += 1
end
if letter_count > largest_letter_count
largest_letter_count = letter_count
mostfreq_letter = letter
end
idx1 += 1
end
return [mostfreq_letter, largest_letter_count]
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts(
'most_common_letter("abca") == ["a", 2]: ' +
(most_common_letter('abca') == ['a', 2]).to_s
)
puts(
'most_common_letter("abbab") == ["b", 3]: ' +
(most_common_letter('abbab') == ['b', 3]).to_s
)
所以在我看来程序应该设置一个字母,然后一旦设置循环通过字符串寻找相同的字母,然后一旦有一个它添加到字母计数然后它判断它是否是最大的字母计数,如果是那些值存储到最终返回值,一旦while循环结束,该值应该是正确的。但是我一直都是假的。我哪里错了?
答案 0 :(得分:0)
您的代码不会向我返回[false, false]
;但它确实返回不正确的结果。 samgak的暗示应该引导你去找虫子。
然而,对于更短的和更多的Rubyish替代方案:
def most_common_letter(string)
Hash.new(0).tap { |h|
string.each_char { |c| h[c] += 1 }
}.max_by { |k, v| v }
end
为每个条目创建一个默认值为Hash
的新0
;迭代字符并计算散列中每个字符的频率;然后找到哪个哈希条目是最大的。当一个哈希被迭代时,它会产生对,就像你想要的函数输出一样,所以这也很好。