DEV Community

Andy Zhao (he/him)
Andy Zhao (he/him)

Posted on

Challenge: Get Closest Number in an Array

Given an array of numbers nums, and a given number given_num:

nums = [100, 200, 400, 800, 1600, 3200, 6400, 128000]
given_num = 900
Enter fullscreen mode Exit fullscreen mode

Get the number closest to the given_num from the array nums.

In this example, the returned value should be 800.

Go!

A black checkered flag signals go!

Top comments (36)

Collapse
 
link2twenty profile image
Andrew Bone • Edited

Javascript:

Let's go for a JS one liner ๐Ÿ˜‰

nums.sort((a, b) => Math.abs(given_num - a) - Math.abs(given_num - b))[0]

This causes the original array to have its order changed but I don't think that's against the rules ๐Ÿ˜…

Collapse
 
bugb profile image
bugb • Edited

I dont think use sort is good idea:
Let see:

[2,3,4,11].sort()
Collapse
 
link2twenty profile image
Andrew Bone

By including a function to sort by I'm no longer doing an alphabetical sort, which means this problem no longer exists.

  console.log([2,3,4,11].sort((a,b)=>a-b));
Output:
  (4)ย [2, 3, 4, 11]

The sort() method sorts the elements of an array in place and returns the array. The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

developer.mozilla.org/en-US/docs/W...

Thread Thread
 
bugb profile image
bugb

yes, by including compareFunction callback, we can solve this problem.

Collapse
 
andy profile image
Andy Zhao (he/him)

If it outputs the closest number, it works! :)

Collapse
 
dmfay profile image
Dian Fay

Window functions!

SELECT unnest
FROM unnest(ARRAY[100,200,400,800,1600,3200,6400,128000])
ORDER BY row_number() OVER (ORDER BY abs(900 - unnest))
LIMIT 1;
Collapse
 
rhymes profile image
rhymes

hahaha thinking outside the box :D

Collapse
 
dmfay profile image
Dian Fay

I looked at it again just now and the row_number is redundant anyway...

SELECT unnest
FROM unnest(ARRAY[100,200,400,800,1600,3200,6400,128000])
ORDER BY abs(900 - unnest)
LIMIT 1;
Collapse
 
andy profile image
Andy Zhao (he/him) • Edited

Ruby:

nums.min_by { |num| (given_num - num).abs }
#=> 800

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.

Collapse
 
joelnet profile image
JavaScript Joel • Edited

This is a job for Reduce!

JavaScript:

const nums = [100, 200, 400, 800, 1600, 3200, 6400, 128000]
const given_num = 900

const closestReducer = g => (a, b) =>
  Math.abs(g - a) < Math.abs(g - b) ? a : b

nums.reduce(closestReducer(given_num))
//=> 800
Collapse
 
hpj1992 profile image
Harshit • Edited

Java:

        int[] nums = {100, 200, 400, 800, 1600, 3200, 6400, 128000};
        int ans = 0;
        int given_num = 900;
        int minDistance = Integer.MAX_VALUE;
        for (int i =0; i < nums.length; i++) {
            int curDistance = Math.abs(nums[i] - given_num);
            if (curDistance < minDistance) {
                ans = nums[i];
                minDistance = curDistance;
            }
        }
        System.out.println(ans);

Trying to optimize no of lines with Java 8 Streams and Lambda.

Collapse
 
lucifer1004 profile image
Gabriel Wu • Edited

Using JavaScript Set:

const closest_num = (nums, given_num) => {
  const min_dist = Math.min(...nums.map(num => Math.abs(num - given_num)))
  return new Set(nums).has(given_num - min_dist) ? given_num - min_dist : given_num + min_dist
}
Collapse
 
lucifer1004 profile image
Gabriel Wu • Edited

Or we can save the intermediate array:

const closest_num = (nums, given_num) => {
  const absolute_dists = nums.map(num => Math.abs(num - given_num))
  const min_absolute_dist = Math.min(...absolute_dists)
  return nums[absolute_dists.indexOf(min_absolute_dist)]
}
Collapse
 
jarvism101 profile image
Aamir Nazir

A Python implementation:

import numpy as np
def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx]

nums = [100, 200, 400, 800, 1600, 3200, 6400, 128000]
given_num = 900

print(find_nearest(nums, given_num))
Collapse
 
mkrl profile image
Mikhail Korolev

Wolfram Language!

Nearest[nums, given_num]
Enter fullscreen mode Exit fullscreen mode

I knew that one day my subscription will come in handy...

Collapse
 
lucifer1004 profile image
Gabriel Wu • Edited

And there is another perspective, instead of iterating numbers, we can iterate distances. Like:

const closest_num = (nums, given_num) => {
  const set = new Set(nums)
  let i = 0
  while (true) {
    if (set.has(given_num - i)) return given_num - i
    if (set.has(given_num + i)) return given_num + i
    i++
  }
}

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:

const benchmark = (func) => {
  console.time(func.name)
  func.call(this, Array.from({length: 10000000}, (v, idx) => (10000000 - idx)), 10000001)
  console.timeEnd(func.name)
}

You can test your function via benchmark(func).

The solution above yields:

closest_num: 5037.456787109375ms

in Chrome.

Collapse
 
pbouillon profile image
Pierre Bouillon • Edited

Here goes Python !

min(nums, key=lambda x: abs(x - given_num))