我目前有以下方法:
def generate_lineups(max_salary)
player_combos_by_position = calc_position_combinations
lineups = []
player_combos_by_position[:qb].each do |qb_set|
unless salary_of(qb_set) > max_salary
player_combos_by_position[:rb].each do |rb_set|
unless salary_of(qb_set, rb_set) > max_salary
lineups << create_team_from_sets(qb_set, rb_set)
end
end
end
end
return lineups
end
player_combos_by_position 是一个散列,包含按位置键控的玩家分组:
{ qb: [[player1, player2], [player6, player7]], rb: [[player3, player4, player5], [player8, player9, player10]] }
salary_of()
获取一组球员并计算他们的总薪水。
create_team_from_sets()
获取一组玩家并返回一个新的玩家团队
理想情况下,我想删除硬编码的嵌套循环,因为我不知道哪些位置可用。我认为递归是答案,但我很难理解解决方案。任何想法将不胜感激。
一些答案建议使用Array#product
. 这通常是一个优雅的解决方案,但是我正在处理非常大的数据集(单独形成大约 161,000 个 WR 组合和大约 5000 个 RB 组合)。在我的循环中,我使用unless salary_of(qb_set, rb_set) > max_salary
检查来避免进行不必要的计算,因为这会淘汰很多。我不能这样做Array#product
,因此这些组合需要很长时间才能组合在一起。我正在寻找尽早排除组合并节省计算机周期的方法。