You may want a compromise between the two extremes of caching the frequencies of all the pairs (which for large data sets will use too much RAM) and caching nothing (which for large data sets will use too much CPU). What about caching just a list of which sets each number occurs in?

#!/usr/bin/perl my @set = map {[split /\s+/]} <DATA>; # We want for each number a list of which sets it's in: for (@set) { for (@$_) { push @{$sets{$_}}, $setnum+0; # +0 numifies undef. } $setnum++ } my ($element, $k) = (1, 3); # or =@ARGV or whatever. { my %count; # Note that this block could be a loop with different # values of $element and $k each time. for (@{$sets{$element}}) { for (uniq(grep { $_ != $element } @{$set[$_]})) { $count{$_}++; } } my @result = (sort { $count{$b} <=> $count{$a} } keys %count)[0..($k +-1)]; print "Results: ", (join ", ", map {"($element, $_)"} @result), $/; } sub uniq { my %used; return grep { !$used{$_}++ } @_ } __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

$;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/

In reply to Re: Best Pairs by jonadab
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.