A hash is not the right structure for this problem. You should use an array:
my @box; for (...) { my ($NetName, $MinX, $MinY, $MaxX, $MaxY) = ...; push @box, [$NetName, $MinX, $MinY, $MaxX, $MaxY, ($MaxX - $MinX) * ($MaxY - $MinY)]; }
and you can sort it as:
@box = sort { $a->[5] <=> $b->[5] } @box;
or if that sort results too slow:
use Sort::Key qw(nkeysort_inplace); nkeysort_inplace { $_->[5] } @box;
Then, you have to look for the N largest areas. It can be done recursively: get the biggest rectangle and look for the N-1 largest, non-overlapping areas.

BTW, "the N largest boxes" is not very precise. Which is larger, a set of rectangles with areas (9, 1) or another with (7, 6)?

I suppose you want to maximize the total area:

# untested! my ($area, @best) = n_largest_boxes(\@box, $n); sub overlap { my ($box1, $box2) = @_; return !( $box1->[3] < $box2->[1] or $box1->[1] > $box2->[3] or $box1->[4] < $box2->[2] or $box1->[2] > $box2->[4] ) } sub n_largest_boxes { my ($boxes, $n, $start, @acu) = @_; my $max = 0; # area for the biggest set of boxes found my @max; # rectangles on the biggest set for ($i = $start || 0; $i + $n <= @$boxes and $boxes->[$i][5] * $n > $max; $i++) { my $box = $boxes->[$i]; next if grep overlap($_, $box), @acu; if ($n > 1) { my $max1, @max1 = n_largest_boxes($boxes, $i+1, $n-1, @acu, $box); if ($max1 and $max1 + $box->[5] > $max) { $max = $max1 + $box->[5]; @max = ($box, @max1); } } else { return ($box->[5], $box); } } return ($max, @max); }

In reply to Re: Sorting hashes... by salva
in thread Sorting hashes... by fiddler42

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.