This discussion is archived
1 Reply Latest reply: Apr 17, 2007 6:51 AM by 807606 RSS

Find the closest Integer to a given Integer in a Vector/List

807606 Newbie
Currently Being Moderated
Hey,

I want to get the index of the element in a vector or list which is the closest value to the given value, BUT THE VALUE SHOULD NOT BE GREATER THAN the given value!

See the example code:
public int getIndexOfClosestEntry(Integer numberToCompare)
{
    Vector<Integer> v = new Vector<Integer>();
    v.add(Integer.valueOf(2);
    v.add(Integer.valueOf(4);
    v.add(Integer.valueOf(8);
    v.add(Integer.valueOf(29);

   //insert Code here to get the closest value to numberToCompare

}
In the example above you can see i have a vector with the values, 2,4,8 and 29. Lets say the parameter numberToCompare is 7. Then i want that the method returns the index "1" because the value 4 is the closest AND NOT GREATER than the given parameter with value 7.

Can anybody help me to find a good solution? (Also mind that the vector can have about 1000 entries or more)

Thanks
  • 1. Re: Find the closest Integer to a given Integer in a Vector/List
    807606 Newbie
    Currently Being Moderated
    Most of these biggest/smallest/greenest/etc problems are got at the same way:

    (1) Start with a sensible value for the "result". Often the first element of the list.

    (2) Write a loop that goes through the list. Compare the list item with the result to see if it is bigger/smaller/greener/etc. If it is it can replace the result.

    (3) Once the loop finishes the result represents the biggest/smallest/greenest/etc element in the list.

    Your version of the problem adds a couple of small details to be resolved: First, as well as the "result" (the biggest/smallest/greenest/etc so far) you have to remember its index in the list. And, secondly, the first element in the list may not be what I described in (1) as a suitable starting value for "result" - indeed you must be prepared to cope with the case where there is no valid index to return from getIndexOfClosestEntry().