Home > Net >  Get closest value in array to variable value
Get closest value in array to variable value

Time:07-27

I have an array of int I'd like to create a function which retrieves from this array the closest value to randomInt


final myArray = [10 , 20, 14, 15, 18, 24];

final int randomInt = 21;

getClosestValueInArray(myArray, randomInt); // should return 20


int getClosestValueInArray(List<int> array, int value) {


}

CodePudding user response:

You could loop through the array and check closeness for each element. E.g. in pseudo-code:

closest = myArray[0]
best_closeness = abs(myArray[0] - randomInt)
for (element in myArray) {
  closeness = abs(element - randomInt)
  if (closeness < best_closeness) {
    closest = element
    best_closeness = closeness
  }
}
return closest

And in Dart (added by @julemand101)

int getClosestValueInArray(List<int> array, int value) {
  int closest = array.first;
  int best_closeness = (closest - value).abs();

  for (int element in array.skip(1)) {
    int closeness = (element - value).abs();

    if (closeness < best_closeness) {
      closest = element;
      best_closeness = closeness;
    }
  }

  return closest;
}

CodePudding user response:

One option is to put these elements in a TreeSet and then use ts.floor(randomInt) and ts.ceil(randomInt) to check what the nearest elements to randomInt is, and pick the one with the smallest absolute difference to randomInt.

Another option is to put these values in a hashset and then search for randomInt - 1, randomInt 1, randomInt - 2 and so on. This again has benefits and drawbacks compared to the previous approach.

There are many other ways.

  •  Tags:  
  • dart
  • Related