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


In reply to Re: Best Pairs by Enlil
in thread Best Pairs by artist

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.