【问题标题】:Sort by Sum the outcome of a combination based on another value in a hash对基于散列中另一个值的组合结果求和排序
【发布时间】:2023-01-27 03:50:52
【问题描述】:

我正在尝试显示 1 个团队和 3 个车手的最高得分组合列表,您需要在其中保持在设定的预算范围内,但按最高分对组合进行排名。每个车手和车队都有价格和积分价值。

目的是列出 1 个团队 + 3 个车手的所有组合,这些组合在目标预算范围内,但根据组合的总分排名。到目前为止,我为以下哈希创建了。包含3名车手和3支车队,并有相应的价格和积分。这些值都是小数,但可以是任何数字:

driver_points = { "john" => 7.0, "mike" => 8.0, "paul" => 9.0 }
driver_price = { "john" => 4.0, "mike" => 5.0, "paul" => 6.0 }

team_points = { "cowboys" => 10.0, "bears" => 11.0, "lions" => 12.0 }
team_price = { "cowboys" => 1.0, "bears" => 2.0, "lions" => 3.0 } 

我已经成功地为此创建了预算/目标元素的组合。下面的代码输出 1 个团队和 3 个车手的组合,加起来小于或等于 20 的预算。

team = team_price.values.permutation(1).to_a
driver = driver_price.values.permutation(3).to_a
target = 20
array = team.product(driver)
res = array.select {|i| i.map(&:sum).sum <= target}.compact
t1 = res.map {|i| i[0]}
d2 = res.map {|i| i[1].flatten.sort}
combo = t1.zip(d2).uniq
@test = combo

这将输出这些组合:

[[[1.0], [4.0, 5.0, 6.0]], [[2.0], [4.0, 5.0, 6.0]], [[3.0], [4.0, 5.0, 6.0]]]

所以这太棒了!我显示的是基于 20 的预算的所有组合。但现在我想根据相应的总分值对每个组合进行排名。例如,如果我们在这里采用第一个组合:

[[1.0], [4.0, 5.0, 6.0]]

这基本上是[[cowboys], [john, mike, paul]]。我想通过积分.因为总分="cowboys" =&gt; 10.0 + "john" =&gt; 7.0 + "mike" =&gt; 8.0 + "paul" =&gt; 9.0。这个组合的总分是34。我很想计算每个组合的分数,然后根据最高分对组合进行排序。最后,我希望用户看到 [[1.0], [4.0, 5.0, 6.0]] 作为组合,而是输出名称。然后是组合旁边的积分和价格总和。所以我的目标是将其作为输出(使用上面显示的组合):

Combo Total Price Total Points
lions, john, mike, paul 18 36
bears, john, mike, paul 17 35
cowboys, john, mike, paul 16 34

编辑

请想象一下,所有数组的值都不止 3 个。我刚刚在每个哈希中使用了 3 作为示例。

【问题讨论】:

    标签: arrays ruby-on-rails ruby ruby-hash


    【解决方案1】:

    您的数据中只有 3 个驱动程序,因此必须全部使用。

    只需将您的车手价格相加,从限额中减去该价格,然后选择低于其余部分的评分最高的团队

      max_price           = 17
    team_names          = team_price.keys
    driver_names        = driver_price.keys
    total_driver_cost   = driver_price.values.sum
    total_driver_points = driver_points.values.sum
    
    team_names.filter_map do |team|
      combination = [team, driver_names].flatten
      total_price = total_driver_cost + team_price[team]
      total_points = total_driver_points + team_points[team]
      next if max_price > target
    
      [combination, total_price, total_points]
    end
    

    回报

    [
      [["cowboys", "john", "mike", "paul"], 16.0, 34.0], 
      [["bears", "john", "mike", "paul"], 17.0, 35.0], 
      [["lions", "john", "mike", "paul"], 18.0, 36.0]
    ]
    

    【讨论】:

    • 抱歉,我仅在哈希中使用 3 作为示例。现实中会有比 3 个车手和车队更多的人。谢谢!
    猜你喜欢
    • 2012-10-09
    • 1970-01-01
    • 2021-12-03
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多