This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
tenshae's profile picture

Closest number in list to another number

Started by tenshae, 01 November 2014 - 10:07 PM
tenshae #1
Posted 01 November 2014 - 11:07 PM
I, for some reason, cannot for the life of me figure out how to get the closest number in a list to another number. What I mean:


function closestNumTo(numlist, number)
	--Code to find closest number in list
end
num = 15
list { 13, 14, 19, 65 }
a = closestNumTo(list, num)
print(a)
OUTPUT: 2 (item number in number array, meaning the second item (14) is closest to the target number (15))


Ideas?

Edit: Just realized this is very badly worded and hard to understand. Sorry! Did my best.
Edited on 01 November 2014 - 10:38 PM
KingofGamesYami #2
Posted 01 November 2014 - 11:39 PM

local function closestTo( tNums, nTarget )
	local nClosest
	local nMaxDiff = math.huge
	for key, num in ipairs( tNums ) do
		nDiff = math.abs( nTarget - num )
		if nDiff < nMaxDiff then
			nMaxDiff, nClosest = nDiff, key
		end
	end
	return nClosest
end
tenshae #3
Posted 01 November 2014 - 11:41 PM

local function closestTo( tNums, nTarget )
	local nClosest
	local nMaxDiff = math.huge
	for key, num in ipairs( tNums ) do
		nDiff = math.abs( nTarget - num )
		if nDiff < nMaxDiff then
			nMaxDiff, nClosest = nDiff, key
		end
	end
	return nClosest
end
Hah, thanks!
KingofGamesYami #4
Posted 01 November 2014 - 11:42 PM
-snip-
Hah, thanks!

No problem! Feel free to ask questions about how it works.
Dragon53535 #5
Posted 02 November 2014 - 01:44 AM
I'll actually get started on asking a question since i do not understand a few of the functions myself. Or well clarifications.

First thing you're doing is initializing nClosest as nil and nMaxDiff as infinity, correct?

Then you're using a for loop to look through the table and subtracting the target by the numerical value of the table and then getting the absolute value of it so that it's positive.

And then if that number is less than nMaxDiff (which it will for the first :P/>) set nMaxDiff to the difference, and nClosest to the value. Did i leave anything out? besides the return of course.
Bomb Bloke #6
Posted 02 November 2014 - 03:15 AM
Your understanding is correct. Well, to the extent that "infinity" can be considered a number - math.huge really represents a number of infinite size.

For large data sets, it may be worth throwing an extra check into the loop allowing an early return if nMaxDiff == 0.