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

Note to all:
Since so many people have mentioned it, the list of epoch times varies. The code example I posted is in a loop which receives a new reference time and list of epoch times.
  • Comment on Re: Find a number in a list closest to a target

Replies are listed 'Best First'.
Re: Re: Find a number in a list closest to a target
by dragonchild (Archbishop) on Jul 25, 2003 at 17:20 UTC
    How large is your list of epoch times? Is it under 100 or over 100? If it's under 100, a linear search would be best, in my opinion, because it's easiest to code up and maintain. If this is speed-critical, where every millisecond counts, then you'll probably want to do something a little more complex.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

      Relatively small, probably under 10 items. That is why I was looking for another way to do it. The hash and sorting was too much overhead for the amount of data. Although I will be processing about 100,000 files daily the data per file (epoch times) will most likely never exceed 5 or 6 items.
        Use a standard linear search looking for a minimum in an unsorted list.
        sub find_min { my ($ctime, @list) = @_; my @best; foreach my $item (@list) { my $diff = abs($ctime - $item); # First time through the loop unless (@best) { @best = ($item, $diff); next; } if ($diff < $best[1]) { @best = ($item, $diff); next; } } return $best[0]; }
        The reason for the array is that you want to associate the best choice so far and why it's the best choice. The reason why I put the next statement in the second if-block is because I practice defensive programming. I don't know when I'm going to modify this loop. If it's not for a while, I might forget that I should've put a next in that second if-block if I'm adding code after it. *shrugs*

        ------
        We are the carpenters and bricklayers of the Information Age.

        Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

        Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.