# Numbers with Arrays

(Excuse the name, I didn’t know how to title this)

Okay, so this is a really stupid post because this should be easy, but basically, I’m trying to make a system that can take a number and decide which value (in an array) is closest, however if the number is not above that value in the array it can’t be that one.

For example, let’s say you need 40 points to get Experienced, and 0 is noob.
If you have let’s say 39 points you will still be a noob, and if you have 40 to the next value you will have Experienced.

If it helps, here’s my code. I for some reason can’t piece the logic together while making it.

local Range = {
["Noob"] = 0,
["Pro"] = 40,
["Seasoned Pro"] = 80
}

local Number = math.random(0, 100)

for i, v in pairs(Range) do
local Math = v-Number
if Math <= Number and v <= Number or v >= Number then
local N = i
print(N)
print(Number)
end
end

Tell me if you see where I went wrong, or how I can fix this so it won’t print out multiple of them.
Like 40 is Pro and 40 is Noob.

local Range = {
["Noob"] = 0,
["Pro"] = 40,
["Seasoned Pro"] = 80
}

local Number = math.random(0, 100)

local ClosestValue = ""
local ClosestDifference = math.huge

for i, v in pairs(Range) do
local Difference = math.abs(v - Number)
if Difference <= ClosestDifference and v <= Number then
ClosestDifference = Difference
ClosestValue = i
end
end

print(ClosestValue)
print(Number)

First, we create the variable ClosestValue that will store the name of the value in the Range table that is closest to the number. We initialize this variable as an empty string. Then, we want to create another variable, ClosestDifference, that will store the smallest difference between the number and any of the values in the Range table. We initialize this variable as math.huge.

Next, we loop through the Range table, and for each value, we compute the absolute difference between the number and the value. If the difference is smaller than the current value of ClosestDifference , and if the value is less than or equal to the number, then we update the values of ClosestDifference and ClosestValue to the current difference and the current key, respectively.

At the end of the loop, ClosestValue will contain the name of the value in the Range table that is closest to the number.

That fixes the issue, thank you!

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