in reply to Finding hash key related to closest value
Output: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";
Max: 302 -> -2.4 151 -> -2.1 165 -> -2.5
|
|---|