in reply to Adding Special Rules to Sort
I don't have any more insight about a head-to-head algorithm, but here's a better way of dealing with an arbitrary number of rule sets. Each rule is defined in a separate subroutine and an array dispatch table is used to evaluate them sequentially. If a rule's result is indeterminate, the next rule is tried. The following code is not rigorously tested, but should give you the idea.
my @teams = qw(mets yankees sox cubs braves cards); my @rules = ( \&wins, \&losses, \&headtohead, \&games, \&tiebreaker ); # games played, wins, losses, ties, tie breaker, teams defeated my %stats = ( braves => [20, 18, 2, 0, 1, {yankees => 1, cubs => 1, etc => 1} + ], yankees => [20, 18, 2, 0, 2, {braves => 1} ], mets => [20, 18, 2, 0, 3, {cubs => 1} ], sox => [20, 8, 12, 0, 4, {yankees => 1} ], cubs => [20, 8, 12, 0, 5, {cards => 1} ], cards => [20, 15, 5, 0, 6, {sox => 1} ] ); my @standing = sort{ my $cv; for (@rules){ $cv = $_->($a, $b); last if $cv; } return $cv; }@teams; print "@teams\n"; print "@standing\n"; ## The Rules: sub wins{ my ($a, $b) = @_; return $stats{$b}[1] <=> $stats{$a}[1]; } sub losses{ my ($a, $b) = @_; return $stats{$a}[2] <=> $stats{$b}[2]; } sub headtohead{ my ($a, $b) = @_; my $win = 0; $win-- if $stats{$a}[5]{$b}; $win++ if $stats{$b}[5]{$a}; return $win; } sub games{ my ($a, $b) = @_; return $stats{$a}[0] <=> $stats{$b}[0]; } sub tiebreaker{ my ($a, $b) = @_; return $stats{$a}[4] <=> $stats{$b}[4]; }
|
|---|