Today, I had the task to match a calculated value with the closest number in a given list. If you don’t mind I’d like to share my solution for others to find if they have the same issue. In case that you know a more performant solution, please feel free to share
So, here’s the setup. We have a list
of unsorted numbers and a single number n
for which we have to find the closest value out of the given list.
list = [10, 7, 14, 20, 1, 47]
n = 35
By looking at the list, one can see that the closest value to 35
is 47
with a “distance” of 12
. Next is 20
with a distance of 15
. I found a StackOverflow answer using the Python min function to find the minimum value in a list based on the result of a function.
Elixir offers the Enum.min_by/4 function, which serves the same purpose. Here is how to use it to solve above problem:
iex> Enum.min_by(list, fn x -> abs(x - n) end)
47
Enum.min_by/4
returns the value which has the minimal absolute distance to the given n
.
And that’s it! Super concise and readable. I hope that this will help somebody