You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails:价格组合转键并按积分排序的实现问题

问题描述

我们已通过代码筛选出符合「1支车队+3名车手」预算限制的价格组合,现有车手、车队的价格/积分哈希集合如下,需完成键名称转换、积分求和、按积分降序排序,最终输出包含组合详情、总价、总积分的结构化表格:

# 车手积分映射
driver_points = { "john" => 20.1, "mike" => 19.3, "paul" => 15.6, "mark" => 1.1 }
# 车手价格映射
driver_price = { "john" => 4.0, "mike" => 5.0, "paul" => 6.0, "mark" => 2.1 }
# 车队积分映射
team_points = { "cowboys" => 20.1, "bears" => 19.3, "lions" => 15.6, "united" => 2.8 }
# 车队价格映射
team_price = { "cowboys" => 1.0, "bears" => 2.0, "lions" => 3.0, "united" => 2.4 }
实现方案(Ruby)

假设筛选后的有效价格组合存储在valid_combinations数组中,每个元素格式为{ team_price: 数值, driver_prices: [数值1, 数值2, 数值3] },处理代码如下:

# 构建价格到名称的反向映射(假设价格无重复)
driver_price_to_name = driver_price.invert
team_price_to_name = team_price.invert

# 转换组合、计算总价与积分
processed = valid_combinations.map do |combo|
  team_name = team_price_to_name[combo[:team_price]]
  driver_names = combo[:driver_prices].map { |p| driver_price_to_name[p] }

  {
    team: team_name,
    drivers: driver_names.join(', '),
    total_price: (combo[:team_price] + combo[:driver_prices].sum).round(2),
    total_points: (team_points[team_name] + driver_names.sum { |n| driver_points[n] }).round(2)
  }
end

# 按总积分降序排序
sorted_combinations = processed.sort_by { |c| -c[:total_points] }
最终输出表格

将排序后的结果整理为Markdown表格(以下为示例,实际内容依有效组合而定):

车队名称车手组合总价总积分
cowboysjohn, mike, mark11.140.5
bearsjohn, mike, mark12.139.7
cowboysjohn, paul, mark12.136.8
bearsjohn, paul, mark13.136.0
lionsjohn, mike, mark13.132.5

内容的提问来源于stack exchange,提问作者ldthompson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 19:05:45