in reply to Re: Re: Re: Find a number in a list closest to a target
in thread Find a number in a list closest to a target
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*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]; }
------
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.
|
|---|