How to find the neareast number from a table?

So basically if i have something like this.

local Table = {
["Test1"] = 10,
["Test2"] = 5,
["Test3"] = 2
}

local randomNumber = Random.new():NextNumber(0,100)

How can i find the closest number to random number from table?

1 Like
local Table = {
["Test1"] = 10,
["Test2"] = 5,
["Test3"] = 2
}

local randomNumber = Random.new():NextNumber(0,100)
local closestdist = math.huge
local closest = nil
for k,v in pairs(Table) do
    local dist = math.abs(v-randomNumber)
    if dist < closestdist then
        closest = k
        closestdist = dist
    end
end 
print(closest)
print(Table[closest])
4 Likes

The quick and dirty way:

Loop through the table, compare the random number to each number, and record the difference.

If the difference between the 2 numbers is the lowest, save that number within the table into a variable.

Repeat until you reach the end of table.

1 Like

There’s really not an efficient way to do this but I do think this is the best as it could get.

  1. Loop through the table.
  2. In a variable store the difference of the random number and the current index.
  3. Check if the difference is lower than the previously stored number.
  4. If it is, set the variable to the new value; else just let it be.
local Table = {
    ["Test1"] = 10,
    ["Test2"] = 5,
    ["Test3"] = 2,
}

local RandomNumber = Random.new():NextNumber(0, 100)

local function FindNearestNumber()
    local Current = math.huge -- math.huge is a very huge number so the difference will obviously be less than that.
    for _, value in Table do -- if you don't define `pairs` or `ipairs`, it will automatically choose the best one
        if math.abs(RandomNumber - value) < Current then -- math.abs just makes any number position (+)
            Current = value -- setting it to be the new value since the difference is less
        end
    end

    return Current -- returning the closest number
end

FindNearestNumber()
1 Like

The gigachad way that puts fear into your enemies:

Assuming the array is sorted by increasing order, you can do a binary search.

Slice an array into 2 halves - if the number is smaller, take the left half and ignore the right. Vice versa otherwise.

Repeat this step until you’re left with 1 number.

It’s much faster than the method others have pointed out, and though this won’t make much difference on small arrays, the speed difference grows as the array grows.

You’ll have to sort the array out first though.

1 Like

No problem guys, i’ve just figured it out. I don’t know if i can share the script for security issues.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.