PJUllrich
Match number with closest value in List
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 ![]()
Popular in Discussions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance










