开发者

Methods for nearby numbers in Groovy

开发者 https://www.devze.com 2023-03-11 06:01 出处:网络
In groovy are there any methods that can find the near by numbers? For example : def list = [22,33,37,56]

In groovy are there any methods that can find the near by numbers? For example :

def list = [22,33,37,56]
def number = 25
//any method to find $number is near to 22 rather than 33.

Is there any method for the above mentioned purpose, or i have to construct my own method or closure for this purpose.

开发者_如何学运维

Thanks in advance.


The following combination of Groovy's collection methods will give you the closest number in the list:

list.groupBy { (it - number).abs() }.min { it.key }.value.first()

The list.groupBy { (it - number).abs() } will transform the list into a map, where each map entry consists of the distance to the number as key and the original list entry as the value:

[3:[22], 8:[33], 12:[37], 31:[56]]

The values are now each a list on their own, as theoretically the original list could contain two entries with equal distance. On the map you then select the entry with the smallest key, take its value and return the first entry of the value's list.

Edit:

Here's a simpler version that sorts the original list based on the distance and return the first value of the sorted list:

list.sort { (it - number).abs() }.first()


If it's a sorted List, Collections.binarySearch() does nearly the same job. So does Arrays.binarySearch().

0

精彩评论

暂无评论...
验证码 换一张
取 消