in reply to Adding Special Rules to Sort

The only reasonable way to evaluate your head to head algorithm is to precompute which head to head comparisons are ambiguous, and which are not.

The way to do that is to calculate the transitive closure of your head to head relation. Suppose you have a hash called %play_result whose keys are the winning teams and whose values are a hash of other teams played and the outcome of the game. Then you would compute the transitive closure as follows:

# This will be our transitive closure. my %is_winning_chain_over; my @new_relations; # First populate with the winners for my $team (keys %play_result) { while (my ($other_team, $won) = each %{$play_result{$team}}) { if ($won) { $is_winning_chain_over{$team}{$other_team} = 1; push @new_relations, [$team, $other_team]; } } } # Now compute the closure while (@new_relations) { my $relation = shift @new_relations; my ($winner, $loser) = @$relation; my $winner_is_over = $is_winning_chain_over{$winner}; my $loser_is_over = $is_winning_chain_over{$loser}; for my $third_team (keys %$loser_is_over) { if (not $winner_is_over->{$third_team}) { $winner_is_over{$third_team} = 1; push @new_relations, [$winner, $third_team]; } } }
And now in your comparison function you can check $play_result{$a}{$b} and not $is_winning_chain_over{$b}{$a} to see if $a should be ahead of $b by the head to head rule, and $play_result{$b}{$a} and not $is_winning_chain_over{$a}{$b} to see if $b should be ahead of $a. (And if neither is true, then go to conditions which are farther down.)

Incidentally for many sports I am fond of the ELO rating system which is much simpler to calculate and takes into account things like whether you were playing hard teams.