in reply to Find a number in a list closest to a target

You could just loop threw comparing the times. No need for hashes and sorting and keys then.

my $BestTime; my $BestOffBy; my $ctime = (stat($key))[10]; print "IN MULTIPLES \$ctime is $ctime\n"; for (@returns) { print "Working Multiple match: $_\n"; my $temp = abs($ctime - $_); if ($temp < $BestOffBy) { $BestOffBy = $temp; $BestTime = $_ } } print "$BestTime is only $BestOffBy away from $ctime.";

I'm not sure this is any better or faster but eliminating the reverse, sort, and keys of the hash could be important if you are checking alot of times.


___________
Eric Hodges

Replies are listed 'Best First'.
Re: Re: Find a number in a list closest to a target
by gnu@perl (Pilgrim) on Jul 25, 2003 at 14:33 UTC
    Yeah, much better. I will be doing this A LOT! Good catch.

      If you will only look up one value against the list, or if the list will vary between lookups, then the linear search will be the best solution.

      But if your list remains static, and you need to compare more than one value against it, it wouldn't take many linear searches before the cost of sorting the static list and performing a binary chop to locate the nearest two values and then determining the minimum offset between the two would be amortised and begin to pay dividends.

      If you need code for this, speak up:)


      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller

        I was reading your posts in about binary trees, but i can't figure out how to read those (crazy golf solutions :-)). Any chance you might show us the light? :-) I searched using the super search with no luck.

        ___________
        Eric Hodges
Re: Re: Find a number in a list closest to a target
by gnu@perl (Pilgrim) on Jul 25, 2003 at 14:53 UTC
    One note though, I had to initialize $BestOffBy = $ctime or the 'if' statement was never entered.