Given an array of numbers nums
, and a given number given_num
:
nums = [100, 200, 400, 800, 1600, 3200, 6400, 128000]
given_num = 900
Get the number closest to the given_num
from the array nums
.
In this example, the returned value should be 800
.
Top comments (36)
Javascript:
Let's go for a JS one liner 😉
This causes the original array to have its order changed but I don't think that's against the rules 😅
I dont think use
sort
is good idea:Let see:
By including a function to sort by I'm no longer doing an alphabetical sort, which means this problem no longer exists.
developer.mozilla.org/en-US/docs/W...
yes, by including compareFunction callback, we can solve this problem.
If it outputs the closest number, it works! :)
Window functions!
hahaha thinking outside the box :D
I looked at it again just now and the
row_number
is redundant anyway...This is a job for Reduce!
JavaScript:
Ruby:
Shamelessly taken from Stack Overflow 🙃 I was in a much more of a "just give me the answer" mood than "let's figure it out" mood.
Java:
Trying to optimize no of lines with Java 8 Streams and Lambda.
A Python implementation:
Wolfram Language!
I knew that one day my subscription will come in handy...
Using JavaScript
Set
:Or we can save the intermediate array:
Here goes Python !
And there is another perspective, instead of iterating numbers, we can iterate distances. Like:
This will normally be slower, but in cases like:
nums = [10000000, 9999999, 9999998, ..., 1]
given_num = 10000001
It will be much faster than other algorithms.
I have written a benchmark function for this:
You can test your function via
benchmark(func)
.The solution above yields:
closest_num: 5037.456787109375ms
in Chrome.