in reply to Best Pairs

Here is my take on this, but you did not mention what to do if the element did not exist at all, nor what to do if you ask for the top 3 elements, but there are 4 elements with the same max count (or 2 elements with the max count, and 3 elements with the next highest count), so the following code just returns the highest amounts found in that case (would return 4 elements, and 5 elements respectively).
#!/usr/bin/perl use strict; use warnings; my $element = 1; my $top = 3; my %matchings; while (<DATA>) { my %seen; my @current_row = grep { !$seen{$_} } split ' ',$_; while ( @current_row ) { my $temp = pop @current_row; for ( @current_row ) { $matchings{$_}{$temp}++; $matchings{$temp}{$_}++; } } } print "(" . join(",", to_list(\%{$matchings{$element}},$top)) . ")\n"; sub top_list { my ($hash,$min_amount) = @_; return "ELEMENT WAS NOT FOUND" unless keys %$hash; my @max_array = sort{$hash->{$b} <=> $hash->{$a}} keys %$hash; my @return_array; while( @return_array < $top ) { return @return_array unless @max_array; push @return_array, shift @max_array; while ( $hash->{$return_array[$#return_array]} == $hash->{$max_arra +y[0]} ) { push @return_array, shift @max_array; last unless @max_array; } } return @return_array; } __DATA__ 2 4 5 7 8 10 1 2 5 6 7 9 2 6 7 8 9 10 1 3 5 10 1 3 4 5 6 8 9 1 2 4 6 1 2 4 5 7 10 1 3 4 6 7 8 9

-enlil