Loading ...
Sorry, an error occurred while loading the content.

Re: [PBML] Finding the closest match in an Array?

Expand Messages
  • kmstitt
    ... closest ... am ... return 3002 ... algorithm ... 777 0095 ... training! ... Thank you for the help, I was able to find a much messier way around the
    Message 1 of 3 , May 3, 2007
    • 0 Attachment
      --- In perl-beginner@yahoogroups.com, merlyn@... wrote:
      >
      > >>>>> "kmstitt" == kmstitt <kris@...> writes:
      >
      > kmstitt> But I cannot seem to get my head around how to find the
      closest
      > kmstitt> number reguardless of if it is higher or lower than what I
      am
      > kmstitt> searching for. So if for example $number = 3000 I need to
      return 3002
      > kmstitt> instead of 2143.
      >
      > If the numbers aren't sorted, you simply need a "high-water-mark
      algorithm"
      > with a linear search.
      >
      > my @list = (4000,2000,3002,2143,5500,90);
      > my $item = 3000;
      >
      > ## first, pick the first item as the best:
      > my $best = $list[0];
      > ## now, see if anything else is closer:
      > for (@list[1..$#list]) {
      > $best = $_ if abs($item - $_) < abs($item - $best);
      > }
      >
      > $best is your result.
      >
      > --
      > Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503
      777 0095
      > <merlyn@...> <URL:http://www.stonehenge.com/merlyn/>
      > Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
      > See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl
      training!
      >


      Thank you for the help, I was able to find a much messier way around
      the problem but I will go back and try your solution out.

      My Messy fix:

      I made two arrays one with all the numbers that were higher than my
      search and another with those that were lower. Then I sorted the
      arrays (Reverse sort for the lower numbered array.) and picked the
      first number out of the array. So now I had my high and low
      numbers. From there I was able to compare the two and figure out
      what was a better match.

      Thanks again for the help.
      -Kris
    Your message has been successfully submitted and would be delivered to recipients shortly.