At 13:00 16/07/99 CDT, Edward M. Perry wrote: > >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? Depending on how densely populated your hash is you might want to use. $key = 5; $i=0; do { $match = $h{$key + $i} || $h{$key - $i}; $i++; } until defined $match; I think this is a gain on something which iterates over all hash keys if the average distance between keys is less than the total number of keys in the hash. That said it could be a very big loss on a sparse hash like this ( 0 => 'dog', 10000 => 'cat', 100000 => 'cow', ) Fergal ==== Want to unsubscribe from Fun With Perl? Well, if you insist... ==== Send email to <fwp-request@technofile.org> with message _body_ ==== unsubscribe