找到最近的值。

我正在寻找一种方法来找到表中最接近 x 的值并返回它。

假设,暂且假定 X 是 x =15,我们有包含 4 个值 {12,190,1,18} 的表格,我该如何使在这种情况下返回第一个键和值?

点赞
用户2223525
用户2223525

我会做这样的事情:

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现在持有最接近值的键
-- values[selectedkey]给你最接近的值(第一个)
2015-05-01 13:11:05
用户2879085
用户2879085
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)
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)
2015-05-01 13:17:12