in reply to Best Pairs

Here is my try. It should be better commented, but the only tricky line is commented, thankfully. :)

I must warn you that it is extremely ugly. I'm sure a more elegant solution is possible. It is instantaneous on your given data set (and returns the right values, joy!). Comments welcome. (I'm a noob so I need all the comments I can get...)

EDIT: The code doesn't exactly work as instructed. It counts combinations when the two numbers are in different lines. Working on a fix...
use warnings; use strict; my %combinations; #hash which holds combination pairs print "Preprocessing data...\n"; while (<>) { chomp; my @line=split; for my $number (@line) { for (@line) { if ($number != $_) { #Disallow combos like (1,1) $combinations{$number}{$_}++; #I saw combo ($number, $_) } } } } for my $number (keys %combinations) { $combinations{$number}=[sort {$combinations{$number}{$b} <=> $combin +ations{$number}{$a}} (keys %{$combinations{$number}})]; #replace our + anonymous hash with an anonymous array containing the combo pairs in + a greatest-to-least order. } print "Hash Initialized. Enter: <number> <quantity> (q to quit)\n"; while (<STDIN>) { chomp; last if /q/; my ($number, $quantity) = split; print "\n"; print "($number, $_)\n" for (@{$combinations{$number}}[0..$quantity-1] +); }
I think that
$combinations{$number}=[sort {$combinations{$number}{$b} <=> $combinat +ions{$number}{$a}} (keys %{$combinations{$number}})];
could be speeded up. I leave that as an exercise for the reader.... :)


Who is Kayser Söze?