【发布时间】:2014-06-10 21:26:45
【问题描述】:
Ruby non-greedy memoized hash,硬币找零解决方案:
def coin_change amt, denom_arr
coins = Hash.new do |coin, key|
coin[key] = if key < denom_arr.min
[]
elsif denom_arr.include? key
[key]
else
denom_arr.
reject { |coin| coin > key }.
reduce([]) { |memo, denom| memo.any? {|coin| coin%denom==0 } ? memo : memo+[denom] }.
map {|denom| [denom] + coin[key-denom]}.
min { |a, b| a.size <=> b.size }
end
end
coins[amt]
end
p coin_change 6, [4,3,1]
#=> [3,3]
究竟是什么被发送到这条线? .reduce([]) { |memo, denom| memo.any? {|coin| coin%denom==0 } ? memo : memo+[denom] }(据我所知,它是一个硬币数组
我也知道如果{|coin| coin%denom==0 } 是真的返回memo 但memo+[denom] 到底是什么?
我了解如果块返回 false 或 nil 以外的值,.any? 方法如何返回 true。
我以为memo 是一个数组,但我在上面调用了类,它返回了Class?
[4,3,8,7].inject([]) { |memo, denom| memo.class }
#=> Class
总之,有人可以用步骤中的示例输出来解释这一点:
- 此行:
.reduce([]) { |memo, denom| memo.any? {|coin| coin%denom==0 } ? memo : memo+[denom] } - 您能否举例说明每次迭代中的递归代码哈希键/值是什么? **
** 即。 denom_arr = 4,3,1 和 amt = 6 在第一遍中,哈希是什么样的?在第二遍时,哈希是什么样的?在第三遍等直到完成......哈希是什么样的?
【问题讨论】:
-
嗯.. codereview.stackexchange.com 也许?
-
@quetzalcoatl 我认为它更适合我,因为 codereview 对我来说表明我理解代码并希望优化它,而 SO 更多的是 帮助我理解这一点 一种论坛。
标签: ruby algorithm recursion hash memoization