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.

Oldest comments (36)
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.
Window functions!
hahaha thinking outside the box :D
I looked at it again just now and the
row_numberis redundant anyway...I probably over complicated it, but here's a CodePen link with how I did it in JS and outputted it to the HTML side.
Long as you solved it! π
Java:
Trying to optimize no of lines with Java 8 Streams and Lambda.
JS:
const nums = [100, 200, 400, 800, 1600, 3200, 6400, 128000];
const givenNum = 900;
nums
.map(n => ({n, d: Math.abs(n-givenNum)}))
.sort((n1, n2) => Math.sign(n1.d - n2.d))[0].n
Rust π¦
Nice, didn't know Rust had similar syntax to Ruby!
With the help of google, I was able to find the answer to this π
import numpy as np
def find_nearest(array, value):
array = np.array(array)
z=np.abs(array-value)
y= np.where(z == z.min())
m=np.array(y)
x=m[0,0]
y=m[1,0]
near_value=array[x,y]
array =np.array([[100, 200, 400, 800, 1600, 3200, 6400, 128000]])
print(array)
value = 900
print(find_nearest(array, value))
Answer:
Thanks for this challenge! πΊ
Wolfram Language!
I knew that one day my subscription will come in handy...
This is a job for Reduce!
JavaScript:
Here goes Python !