|
| 1 | +#Problem: https://exercism.org/tracks/ruby/exercises/tournament |
| 2 | + |
| 3 | +#Solution |
| 4 | +class Tournament |
| 5 | + def self.tally(input) |
| 6 | + matches = input.split("\n") |
| 7 | + point_table = {} |
| 8 | + matches.each do |match_str| |
| 9 | + team1,team2,result = match_str.split(";") |
| 10 | + self.set_team_data(team1,point_table) unless point_table.has_key?(team1) |
| 11 | + self.set_team_data(team2,point_table) unless point_table.has_key?(team2) |
| 12 | + point_table[team1][:MP]+=1 |
| 13 | + point_table[team2][:MP]+=1 |
| 14 | + if result == "win" |
| 15 | + point_table[team1][:W]+=1 |
| 16 | + point_table[team1][:P]+=3 |
| 17 | + point_table[team2][:L]+=1 |
| 18 | + elsif result=="loss" |
| 19 | + point_table[team2][:W]+=1 |
| 20 | + point_table[team2][:P]+=3 |
| 21 | + point_table[team1][:L]+=1 |
| 22 | + elsif result=="draw" |
| 23 | + point_table[team1][:D]+=1 |
| 24 | + point_table[team2][:D]+=1 |
| 25 | + point_table[team1][:P]+=1 |
| 26 | + point_table[team2][:P]+=1 |
| 27 | + else |
| 28 | + raise InputError |
| 29 | + end |
| 30 | + end |
| 31 | + self.format_scorebaord(point_table) |
| 32 | + end |
| 33 | + |
| 34 | + private |
| 35 | + def self.set_team_data(team,point_table) |
| 36 | + point_table[team] = { "MP":0, "W":0, "L":0 , "D":0, "P":0 } |
| 37 | + end |
| 38 | + |
| 39 | + def self.format_scorebaord(point_table) |
| 40 | + point_table = point_table.sort_by{|team,score| [-score[:P],team]} |
| 41 | + formatted = point_table.map do |team, result| |
| 42 | + played = result[:MP].to_s.rjust(2) |
| 43 | + points = result[:P ].to_s.rjust(2) |
| 44 | + wins = result[:W ].to_s.rjust(2) |
| 45 | + draws = result[:D ].to_s.rjust(2) |
| 46 | + losses = result[:L ].to_s.rjust(2) |
| 47 | + "#{team.ljust(30)} | #{played} | #{wins} | #{draws} | #{losses} | #{points}\n" |
| 48 | + end |
| 49 | + header = "Team | MP | W | D | L | P\n" |
| 50 | + header + formatted.join |
| 51 | + end |
| 52 | +end |
0 commit comments