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.
PostgreSQL:
In the case where two records share the same value for "abs(4 - id)" the output would be in-determinant and perhaps not a constant. To fix that I suggest something like the untested guess:
This solution provides performance on the order of O(N log N), where O(log N) is possible for example: https://stackoverflow.com/a/8900318/1153319
Some C# Linq ones... too many ways to do this!
Even more ways if you use a list instead, since plain ol arrays have no .Sort()
Python by me and https://stackoverflow.com/users/29253/igorgue based on some of the other answers here. Only 34 characters:
Some of you don't seem to be reading that the list is
unordered
(although with the example as it is I can understand your confusion). In Java:Not exactly terse but hey its Java.
Language: C, Char count: 79
Signature:
Usage: