Friday, 27 September 2013

Trying to create nested loops dynamically in Ruby

Trying to create nested loops dynamically in Ruby

I currently have the following method:
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 is a hash that contains groupings of players
keyed by position:
{ qb: [[player1, player2], [player6, player7]], rb: [[player3, player4,
player5], [player8, player9, player10]] }
salary_of() takes the sets of players and calculates their total salary.
create_team_from_sets() takes sets of players and returns a new Team of
the players
Ideally I want to remove the hardcoded nested loops as I do not know which
positions will be available. I think recursion is the answer, but I'm
having a hard time wrapping my head around the solution. Any ideas would
be greatly appreciated.

No comments:

Post a Comment