Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding closest match in collection of numbers [closed]

So I got asked today what was the best way to find the closes match within a collection.

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

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

What number is closest to 4?

Collection is numerical, unordered and can be anything. Same with the number to match.

Lets see what we can come up with, from the various languages of choice.


2 Answers

11 bytes in J:

C=:0{]/:|@-

Examples:

>> a =: 1 3 8 10 13
>> 4 C a
3
>> 11 C a
10
>> 12 C a
13

my breakdown for the layman:

0{         First element of
]          the right argument
/:         sorted by
|          absolute value 
@          of
-          subtraction
like image 82
2 revsJimmy Avatar answered Sep 13 '25 05:09

2 revsJimmy


Shorter Python: 41 chars

f=lambda a,l:min(l,key=lambda x:abs(x-a))
like image 41
Kenan Banks Avatar answered Sep 13 '25 06:09

Kenan Banks