gpt4 book ai didi

ruby-on-rails - 数组不返回最频繁的值

转载 作者:太空宇宙 更新时间:2023-11-03 18:13:10 24 4
gpt4 key购买 nike

def most_common_letter(string)
letter = nil
final_letter = nil
letter_count = nil
idx1 = 0
idx2 = 0
count = 0
while idx1 < string.length
letter = string[idx1]
while idx2 < string.length
if letter == string[idx2]
count += 1
end
idx2 += 1
end
if (letter_count == nil) || (count > letter_count)
letter_count = count
final_letter = letter
end
idx1 += 1
end
arr = []
arr.push(final_letter)
arr.push(letter_count)
return arr
end

puts(most_common_letter("abbab") == ["b", 3])
#should be true

不断获取 [a,2] 这让我相信它只是在执行部分代码,而在我看来代码应该在每次出现更频繁的字母时重置最终字母的值和字母计数。我哪里出错了?

最佳答案

这种类型的问题通常使用计数哈希:

def most_frequent_letter(str)
str.each_char.with_object(Hash.new(0)) { |c,h| h[c] += 1 }.max_by(&:last)
end

most_frequent_letter("bananas are so-so")
#=> ["a",4]

步骤:

h = "bananas are so-so".each_char.with_object(Hash.new(0)) { |c,h| h[c] += 1 }
#=> {"b"=>1, "a"=>4, "n"=>2, "s"=>3, " "=>2, "r"=>1, "e"=>1, "o"=>2, "-"=>1}
h.max_by(&:last)
#=> ["a",4]

关于ruby-on-rails - 数组不返回最频繁的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30384204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com