This might be overkill but here's a way to do it using a DB_File in memory BTREE database. It works by inverting the original hash and allows for duplicate values (now keys) by setting the R_DUP flag. See the
docs for how you would deal with duplicates:
use DB_File ;
my %hash = (
'-2.6' => 72,
'-2.5' => 165,
'-2.4' => 302,
'-2.3' => 168,
'-2.2' => 260,
'-2.1' => 151,
# ...etc.
);
$DB_BTREE->{'compare'} = sub { $_[0] <=> $_[1] };
$DB_BTREE->{'flags'} = R_DUP;
my %h;
my $db = tie %h, "DB_File", undef, undef, undef, $DB_BTREE;
while (my($k,$v) = each %hash) {
$h{$v} = $k;
}
my ($key,$value,$half);
# get the max
$db->seq($key, $value, R_LAST);
print "Max: $key -> $value\n";
$key = $half = $key / 2;
# get the nearest to half
$db->seq($key, $value, R_CURSOR);
print "$key -> $value\n";
$key <= $half ? $db->seq($key, $value, R_NEXT)
: $db->seq($key, $value, R_PREV);
print "$key -> $value\n";
Output:
Max: 302 -> -2.4
151 -> -2.1
165 -> -2.5
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.