Search code examples
javaarraysgroovy

Assign a value to a index in an array


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]

Solution

  • 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].