in reply to Search a hash for closest match
I don't really follow your example, but as best as I can tell, your search algorithm should look something like
#!/usr/bin/perl -w use strict; my @values = ( 15, 49, 51, 79, ); my $pos = 50; my $diff; my @results; for my $value (@values) { if (not defined $diff or abs($pos - $value) < $diff) { $diff = abs($pos - $value); @results = $value; } elsif (abs($pos - $value) == $diff) { push @results, $value; } } print join "\n", @results;
Note that there are more efficient search procedures, but this may be good enough before you profile.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Search a hash for closest match
by aquinom (Sexton) on Nov 01, 2011 at 17:44 UTC | |
by kennethk (Abbot) on Nov 01, 2011 at 18:00 UTC | |
by aquinom (Sexton) on Nov 01, 2011 at 18:06 UTC | |
by kennethk (Abbot) on Nov 01, 2011 at 18:47 UTC |