Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I find the smallest difference between 2 numbers in a table?

Asked by
Protune 15
8 years ago

Basically, let's assume I have a table and a number to compare it with.


local Table = {1,2,5,8,20} local Number = 4

How do I compare the table with the number, to return the value in the table closest to the number I first provided? (In this case, it would return 5.)

Disregard the fact that if I would enter 3, for example, it would try to return 2 numbers. I'll filter the table out beforehand to remove any numbers that are lower then the provided number

1 answer

Log in to vote
0
Answered by
Kryddan 261 Moderation Voter
8 years ago

Something I came up with was, first use a for loop that goes through all the numbers inside the Table. Then check if the current number in the Table is less than Number, if so then subtract Number with the current selected Table number. If it's greater then just do the other way around. I also made a separate table where I stored the new numbers and then I used table.sort to get them in order.

Some useful links:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ http://wiki.roblox.com/index.php?title=Function_dump/Table_manipulation http://wiki.roblox.com/index.php?title=Loops

local Table = {1,2,5,8,20}
local Number = 4
local difference = {}

for i = 1, #Table do
    if Table[i] < Number then
        print(Number - Table[i])
        table.insert(difference, Number - Table[i])
    else
        print(Table[i] - Number)
        table.insert(difference, Table[i] - Number)
    end
end

table.sort(difference)

for i = 1, #difference do --Just for testing
    print(difference[i]) --would print out 1,2,3,4,16
end

Is this what you were after?

Ad

Answer this question