Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Return the closest number in a list to a given value

Posted on 2006-04-06
14
Medium Priority
?
460 Views
Last Modified: 2010-03-31
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
0
Comment
Question by:DanBAtkinson
  • 9
  • 5
14 Comments
 
LVL 92

Assisted Solution

by:objects
objects earned 2000 total points
ID: 16397289
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
 

Author Comment

by:DanBAtkinson
ID: 16397314
Thanks. Looking at abs in the API, how can I determine the difference between two numbers if I can only pass one?
0
 

Author Comment

by:DanBAtkinson
ID: 16397320
D'OH.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 92

Expert Comment

by:objects
ID: 16397348
int diff = (int) Math.abs(a - b);
0
 

Author Comment

by:DanBAtkinson
ID: 16397362
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
 

Author Comment

by:DanBAtkinson
ID: 16397367
I'm always dealing with integers here so is there a need for Math.abs, or am I misunderstanding something?
0
 
LVL 92

Accepted Solution

by:
objects earned 2000 total points
ID: 16397393
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
 

Author Comment

by:DanBAtkinson
ID: 16397442
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
 

Author Comment

by:DanBAtkinson
ID: 16397477
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
 

Author Comment

by:DanBAtkinson
ID: 16397592
objects: Do you have any idea how I could get the correct output which corresponds to the array?
0
 

Author Comment

by:DanBAtkinson
ID: 16397678
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
 
LVL 92

Expert Comment

by:objects
ID: 16397776
no worries (sorry, I stepped out for lunch)
0
 

Author Comment

by:DanBAtkinson
ID: 16397829
lol! It's ok!

It's 05:20 here! What I wouldn't give for a Subway about now!! :-)
0
 
LVL 92

Expert Comment

by:objects
ID: 16397884
We got spoiled with Yum Cha today :)
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn different types of Android Layout and some basics of an Android App.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month13 days, 15 hours left to enroll

580 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question