Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the closest number in a random set

Say I got a set of 10 random numbers between 0 and 100.

An operator gives me also a random number between 0 and 100. Then I got to find the number in the set that is the closest from the number the operator gave me.

example

set = {1,10,34,39,69,89,94,96,98,100}

operator number = 45

return = 39

And how do translate this into code? (javascript or something)

like image 509
Andy Jacobs Avatar asked Dec 06 '22 04:12

Andy Jacobs


1 Answers

if set is ordered, do a binary search to find the value, (or the 2 values) that are closest. Then distinguish which of 2 is closest by ... subtracting?

If set is not ordered, just iterate through the set, (Sorting it would itself take more than one pass), and for each member, check to see if the difference is smaller than the smallest difference you have seen so far, and if it is, record it as the new smallest difference, and that number as the new candidate answer. .

  public int FindClosest(int targetVal, int[] set)
  {
      int dif = 100, cand = 0;
      foreach(int x in set)
          if (Math.Abs(x-targetVal) < dif)
          {
              dif = Math.Abs(x-targetVal);
              cand = x;
          }
      return cand;
  }
like image 189
Charles Bretana Avatar answered Dec 23 '22 19:12

Charles Bretana