我有一个散列,如下所示:
hash = {
"Hulk" => 25,
"IronMan" => 75,
"Groot" => 51,
"Captain America" =>50,
"Spider Man" => 40,
"Thor" => 50,
"Black Panther" => 49
}
我需要找到一组超级英雄,当我和其他人的价值相加时,他们的价值将是100,例如,美国队长+雷神= 100。
我可以使用以下索引遍历散列:
hash.each_with_index { |(key,value),index| ... }
内部循环比较每个值。
有没有更好、更简单的方法来解决这个问题?
发布于 2018-09-14 02:11:48
如果输入不是很大,可以使用Array#combination
1.upto(input.size).
flat_map do |i|
input.to_a.combination(i).select do |arrs|
arrs.map(&:last).reduce(:+) == 100
end
end.
map(&:to_h)
#⇒ [{"Hulk"=>25, "IronMan"=>75},
# {"Groot"=>51, "Black Panther"=>49},
# {"Captain America"=>50, "Thor"=>50}]
如果您确定只有2位英雄的力量可以归结为100
,那么在combination
的参数中用硬编码的2
替换1.upto(input.size)
循环。在这种情况下,它将足够快,即使是巨大的投入。
发布于 2018-09-14 02:16:37
您可以从性能上实现线性复杂度O(N)
。
编辑我假设您正在寻找2的组合,据我理解,这是不正确的。
input = {
"Hulk" => 25,
"IronMan" => 75,
"Groot" => 51,
"Captain America" => 50,
"Spider Man" => 40,
"Thor" => 50,
"Black Panther" => 49
}
# Create inverse lookup map
inverse_input = input.each.with_object(Hash.new([])){ |(k, v), h| h[v] += [k] }
#=> {25=>["Hulk"], 75=>["IronMan"], 51=>["Groot"], 50=>["Captain America", "Thor"], 40=>["Spider Man"], 49=>["Black Panther"]}
input.flat_map do |hero, power|
# Get heroes with needed power only
other_heroes = inverse_input[100 - power]
# Remove current hero from the list
other_but_this = other_heroes.reject{ |name| name == hero }
# Map over remaining heroes
# and sort them for later `uniq` filtering
other_but_this.map { |h| [hero, h].sort }
end.compact.uniq
# compact will remove nils
# uniq will remove duplicates
#=> [["Hulk", "IronMan"], ["Black Panther", "Groot"], ["Captain America", "Thor"]]
如果输入的长度较小,则可以使用更短的O(N^2)
解决方案:
input.to_a.
permutation(2).
select{|(n1,v1), (n2, v2)| n1 != n2 && v1 + v2 == 100 }.
map{ |l,r| [l.first, r.first].sort }.
uniq
#=> [["Hulk", "IronMan"], ["Black Panther", "Groot"], ["Captain America", "Thor"]]
发布于 2018-09-14 02:08:58
一种可能的解决办法是:
all_options = input.map { |a| input.without(a).map { |b| [a, b] } }.flatten(1).sort.uniq
valid_options = all_options.select { |r| r.sum(&:second) == 100 }
修改后,第一行可以使用input.combination(2)
(oops)实现。整个问题可以通过以下方法解决:
input.combination(2).select { |r| r.sum(&:second) == 100 }.map(&:to_h)
https://stackoverflow.com/questions/52329620
复制相似问题