Finding the Closest Number to a Given One in an Array

Hello!

How would I create a function which finds and returns the closest number to a given one in an array?
So let’s say I had an array with the values of 5, 2, 3 and 8 and I wanted to get the closest number to 4.
So that’ll return 5.

This is a simple algorithm, looping through the array, keeping track of the closest number to 4 so far, seeing if the next number has a smaller difference becoming the new closest one. At the end the number that ended in the variable we used to keep track, is the closest.

local closest = math.huge
local number = 4

for _, otherNumber in pairs(array) do
    if math.abs(number - otherNumber) < math.abs(number - closest) then
        closest = otherNumber
    end
end

print(number)

The closest variable keeping track of the current closest number is initialized as math.huge, this is a common pattern. The idea is if I did math.abs(4-math.huge), the result would always be math.huge, which is guaranteed to be larger than any other number in the array, and hence guaranteed to not be the end result. It’s a nice way to not add a check to see if there was not closest, in which case the current number is automatically the current closest.

math.abs(a-b) will basically find the distance between two numbers, mind you the distance, and not the difference. The difference between 2 and 4 is -2, assuming you mean 2-4 = -2, but the distance is 2. If we did not abs, then 8 would be considered closer, since 8-4 = 4 > -2, which is not the case.

10 Likes

I see, never mind me wanting to return 3, 5 works for my use case. Thank you for your detailed explanation, you have a very clever method!

1 Like
2 Likes

My question has already been answered, but thank you for your reply!

I know, I’m just reminding you that you should use the search feature before creating a thread.

I did use it! But I didn’t find that post.

That’s strange because I searched for threads using the same keywords you’ve used in this thread’s title and found the following.

Yeah. When originally searching, I didn’t search for those exact titles. Mostly searched for what my title is. The search results I saw weren’t of much use.