Reputation: 369
I have an array having integers
int[] cells= new int[6]
cells[0] = 0
cells[1] = 0
cells[2] = 215
cells[3] = 230
cells[4] = 243
cells[5] = 252
I am trying to check an other number in this array and assign to which index it belongs. For example: if I used the number 243 i wanted cell 4 from numbers 243. This works absolutely fine my below code, if mynumber is 220 it assigns for 215. But the problem is, If my number is 225 it assigns to 230. Which is aslo right in finding the closest. But i would like to assign 225 into 215(index #2) instead of 230. It should assign only if the number is 230 or if it falls in range 230-242. what is the best way to get it. Please help.
My Code is :
def mynumber = 225
int distance = Math.abs(cells[0] - mynumber )
int idx = 0
for(int c = 1; c < cells.length; c++)
{
int cdistance = Math.abs(cells[c] - mynumber )
if(cdistance < distance)
{
idx = c
distance = cdistance
}
}
int choosennumber= cells[idx]
Upvotes: 1
Views: 1449
Reputation: 590
This is an irresistable opportunity to use TreeMap
:
TreeMap<int, int> map = new TreeMap<int, int>([0: 1, 215: 2, 230: 3, 243: 4, 252: 5])
int idx = map.lowerEntry(225).value
assert idx == 2
Upvotes: 0
Reputation: 37008
You can make use of the min/max
functions, that Groovy brings for
collections. You basically want the largest number out of your list, that
is smaller than your limit.
def findLimit(list, limit) {
list.max{ it <= limit ? it : -it }
}
def cells = [ 242, 215, 230, 243, 252, 244]
assert 215 == findLimit(cells, 10)
assert 215 == findLimit(cells, 225)
assert 243 == findLimit(cells, 243)
assert 252 == findLimit(cells, 1000)
Note: If the list is sorted, a for
loop and short-circuiting once the
limit is reached is more efficient.
Upvotes: 2
Reputation: 29
Don't use Math.abs; get the difference between the tow numbers and keep the positive value, in that way you will find 215 and not 230.
int distance = cells[0] - mynumber
and
int cdistance = cells[c] - mynumber
Upvotes: 1
Reputation: 393821
You want mynumber
to be >= the number in the current index of the array:
int distance = mynumber - cells[0];
int idx = 0;
for(int c = 1; c < cells.length; c++) {
if (mynumber >= cells[c]) {
int cdistance = mynumber - cells[c];
if (cdistance < distance) {
idx = c;
distance = cdistance;
}
}
}
int choosennumber = cells[idx];
This is assuming mynumber >= cells[0]
.
Upvotes: 2