[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] Closest hash value




Here is the problem: given a key ($key), and a hash (%h), I want the value
of the closest hash key. I came up with this which is only moderately fun.
Really it works pretty well, assuming keys are numeric and the hash is
small. Mapping to %temp is weak.  

An array seems unreasonable because in reality the keys (or indicies) are
large and the array would be very sparse.

$key  = 5;
%h    = (1=>'one', 2=>'two', 4=>'four', 8=>'eight');

%temp = map { abs($_-$key) => $_ } keys %h;
$val  = $h{$temp{(sort({$a<=>$b} keys %temp))[0]}};

Any ideas?

Ed Perry

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe