Return the closest number in a list to a given value

Hi there.

The question is simple really.

I have a list which adds a integers in a loop to it based on the outcome of certain conditions. At the end of that loop, I want to find out which is the closest number in that list to a value I already have.

How would I do that?

Example:

int myInt = 13;

myList (after going through the loop) = {1,16,20,31,2,12,4}

getClosestNumber(myInt, myList)

public int getClosestNumber(int value, List valueList)
{
  run marvellous check I don't know how to do.

  return int; //In this case 12. If there are two numbers (ie, if 14 is also in the list, return the lowest number).
}

Thanks in advance
DanBAtkinsonAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

objectsCommented:
loop thru your list
and calculate the absolute difference between each element and your value (use Math.abs() to get absolute value)
and store the smallest abs diff (use Math.min()) to compare with best so far
Initialise best so far as large numebr eg. Integer.MAX_VALUE
0
DanBAtkinsonAuthor Commented:
Thanks. Looking at abs in the API, how can I determine the difference between two numbers if I can only pass one?
0
DanBAtkinsonAuthor Commented:
D'OH.
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

objectsCommented:
int diff = (int) Math.abs(a - b);
0
DanBAtkinsonAuthor Commented:
for (int i=0;i<closer.size();i++)
{
      int temp = Math.abs((Integer)closer.get(i));
      closer.remove(i);
      closer.add(temp);
}

Am I on the right track with this?

First getting them and then converting them into absolutes?
0
DanBAtkinsonAuthor Commented:
I'm always dealing with integers here so is there a need for Math.abs, or am I misunderstanding something?
0
objectsCommented:
you don't need to add/remove, and you need to calc the diff between each element and you value

int bestdiff = Integer.MAX_VALUE
int closest = -1;
 for (int i=0;i<closer.size();i++)
{
     int n = (Integer)(closer.get(i)).intValue();
     int diff = Math.abs(value - n);
     // now check if it diff is less than bestdiff
     // if so set bestdiff to be diff
     // and closest to be n
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
DanBAtkinsonAuthor Commented:
OK.

So:

if (closer.size()>0)
{
      int bestdiff = Integer.MAX_VALUE;
      int closest = -1;
      for (int i=0;i<closer.size();i++)
      {
            int n = (Integer)(closer.get(i));
            int diff = Math.abs(departIndex - n);
            if (diff <bestdiff)
            bestdiff = diff;
      }
      System.out.println("Closest: "+bestdiff);



Does that look right to you?!
0
DanBAtkinsonAuthor Commented:
No. It's not right. :-)
Neither's this. :-(

System.out.println("Closest: "+info2[(Integer)closer.get(bestdiff)]);

I rewrote it to this because I need to return a value from an array (whose index corresponds to the value in the 'closer' list.

Does this make sense, and am I going in the right direction?
0
DanBAtkinsonAuthor Commented:
objects: Do you have any idea how I could get the correct output which corresponds to the array?
0
DanBAtkinsonAuthor Commented:
Never mind...


        for (int i=0; i < stations.length; i++)
        {
           if (stations[i].contains(searchTerm))
                    {
                               System.out.println("Found: "+interchanges[i]);                        
                              closer.add(i);
                    }
        }
                      if (closer.size()>0)
                    {
                        int bestdiff = Integer.MAX_VALUE;
                        for (int i=0;i<closer.size();i++)
                        {
                              int n = (Integer)(closer.get(i));
                              int diff = Math.abs(departIndex - n);
                              if (diff <bestdiff)
                              {
                                    bestdiff = diff;
                              }
                        }                        
                        int interchangeStation = (Math.max(departIndex,bestdiff)-Math.min(departIndex,bestdiff));


This provides the answer I'm looking for.

Thanks very much again objects!
0
objectsCommented:
no worries (sorry, I stepped out for lunch)
0
DanBAtkinsonAuthor Commented:
lol! It's ok!

It's 05:20 here! What I wouldn't give for a Subway about now!! :-)
0
objectsCommented:
We got spoiled with Yum Cha today :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.