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

Re: [FWP] Closest hash value



>>>>> "EMP" == Edward M Perry <eperry@learjet.com> writes:

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

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

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

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

EMP> Any ideas?

Since you want to avoid the memory for copies how about just walking
the keys?

	do { $best = $_; last} for keys %h;
	do { $best = $_ if abs($_ - $key) < abs($best - $key) } for (keys %h);

An auxilary variable could be used to avoid the extra calculation. Or
change the initialization to simply set $best to the highest possible
value.

<random thought>
If Hashes could be accessed like arrays getting the first key could be
a nice touch here.
</random thought>

<chaim>
-- 
Chaim Frenkel					     Nonlinear Knowledge, Inc.
chaimf@pobox.com				               +1-718-236-0183

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