using jquery, how would i find the closest match in an array, to a specified number

前端 未结 2 1302
太阳男子
太阳男子 2020-12-03 12:12

using jquery, how would i find the closest match in an array, to a specified number

For example, you\'ve got an array like this:

1, 3, 8, 10, 13, ...

2条回答
  •  独厮守ぢ
    2020-12-03 12:47

    Here's a generalized version, taken from: http://www.weask.us/entry/finding-closest-number-array

    int nearest = -1;
    int bestDistanceFoundYet = Integer.MAX_INTEGER;
    // We iterate on the array...
    for (int i = 0; i < array.length; i++) {
       // if we found the desired number, we return it.
       if (array[i] == desiredNumber) {
          return array[i];
       } else {
          // else, we consider the difference between the desired number and the current number in the array.
          int d = Math.abs(desiredNumber - array[i]);
          if (d < bestDistanceFoundYet) {
             // For the moment, this value is the nearest to the desired number...
             nearest = array[i];
          }
       }
    }
    return nearest;
    

提交回复
热议问题