找到最接近的值
Find the nearest value
我正在寻找一种方法来找出哪个值最接近 table 和 return 中的 x。
让我们暂时假设 X 是 x=15,我们有 table 有 4 个值 {12, 190, 1, 18},在这种情况下我如何做到这一点第一个key&value 是 returned?
我会这样做:
initialdiff = 1000000000000
selectedkey = -1
values = {12, 190, 1, 18}
x = 15
for key, val in pairs (values) do
currentdiff = math.fabs(val - x)
if (currentdiff < initialdiff) do
initialdiff = currentdiff
selectedkey = key
end
end
-- selectedkey now holds key for closest match
-- values[selectedkey] gives you the (first) closest value
x = 15
table = {190, 1, 12, 18}
function NearestValue(table, number)
local smallestSoFar, smallestIndex
for i, y in ipairs(table) do
if not smallestSoFar or (math.abs(number-y) < smallestSoFar) then
smallestSoFar = math.abs(number-y)
smallestIndex = i
end
end
return smallestIndex, table[smallestIndex]
end
index, value = NearestValue(table,x)
print(index)
print(value)
我正在寻找一种方法来找出哪个值最接近 table 和 return 中的 x。
让我们暂时假设 X 是 x=15,我们有 table 有 4 个值 {12, 190, 1, 18},在这种情况下我如何做到这一点第一个key&value 是 returned?
我会这样做:
initialdiff = 1000000000000
selectedkey = -1
values = {12, 190, 1, 18}
x = 15
for key, val in pairs (values) do
currentdiff = math.fabs(val - x)
if (currentdiff < initialdiff) do
initialdiff = currentdiff
selectedkey = key
end
end
-- selectedkey now holds key for closest match
-- values[selectedkey] gives you the (first) closest value
x = 15
table = {190, 1, 12, 18}
function NearestValue(table, number)
local smallestSoFar, smallestIndex
for i, y in ipairs(table) do
if not smallestSoFar or (math.abs(number-y) < smallestSoFar) then
smallestSoFar = math.abs(number-y)
smallestIndex = i
end
end
return smallestIndex, table[smallestIndex]
end
index, value = NearestValue(table,x)
print(index)
print(value)