如何从阵列的优化选择 [英] How to get the optimized choice from arrays
问题描述
我有散列(比方说,我有三个),如下的几个数组:
I have several arrays of hashes (let's say I have three) as follows:
a = [{ cost: 10, value: 20},
{ cost: 9, value: 20},
{ cost: 10, value: 22},
{ cost: 2, value: 10}
]
b = [{ cost: 4, value: 20},
{ cost: 9, value: 20},
{ cost: 15, value: 22},
{ cost: 12, value: 10}
]
c = [{ cost: 10, value: 21},
{ cost: 9, value: 20},
{ cost: 10, value: 22},
{ cost: 3, value: 10}
]
我需要找出哪些选择哈希,从每个阵列,给我的的最高金额:值
保存的总和:成本
根据给定值(比方说 30
)。
I need to find out which choice of hashes, one from each array, gives me the maximum sum of :value
keeping the sum of :cost
under a given value (let's say 30
).
答案是这种情况下,只要看一眼可能容易,但是这仅仅是示例数据和在现实中我有更多的阵列。有人可以帮助我,或点我朝着正确的方向?
The answer is probably easy for this case just looking at it, but this is just sample data and in reality I have many more arrays. Can someone help me or point me in the right direction?
编辑:我应该还提到,我喜欢做与对象的这个阵列。我使用哈希作为一个例子,因为它会更容易来形容,但我计划使用对象。此外,如果一个对象被从阵列中的一个应用,我想它相同的选项,不会从其他阵列使用,因此每个选定的对象必须是唯一的。
I should also mention that I'd like to do with this arrays of objects. I used hashes as an example since it would be easier to describe, but I'm planning on using Objects. Also, if an Object gets used from one of the arrays, I'd like it identical options to not be used from the other arrays so each selected Object should be unique.
推荐答案
下面是一个班轮:
a.product(b,c).select{ |arr| arr.reduce(0) { |sum,h| sum + h[:cost] } < 30 }.max_by{ |arr| arr.reduce(0){ |sum,h| sum + h[:value]} }
破碎了一下:
Broken up a bit:
a.product(b,c)
.select{ |arr| arr.reduce(0) { |sum,h| sum + h[:cost] } < 30 }
.max_by{ |arr| arr.reduce(0) { |sum,h| sum + h[:value] } }
这篇关于如何从阵列的优化选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!