首页 > 解决方案 > 从 Lua 中的表中选择 N 个均匀分布的元素

问题描述

我正在尝试编写一个程序,该程序将从给定的整数数组中均匀选择 N 个数字

我的尝试是基于这篇文章的 Lua 实现: https ://stackoverflow.com/a/2451363

我更改local step = (tableLen-1)/(n-1)local step = (tableLen-2)/(n-1) 因为在 Lua 表中从 1 开始(在更改之前它也不起作用)。我有奇怪的结果。例如,当我尝试从数组中选择 3 个数字时,当数组的最高成员为 20 时,它将选择 27。我认为问题可能在于tableLen-2我在(0 对 1)处开始 for 循环的索引或索引。

这是我的代码

myTable = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}

local tableLen = table.getn(myTable) --20

local n = 3

print("choosing " .. n .. " numbers")

local step = (tableLen-2)/(n-1)

local count = 0

for i=0,n,1 do
    count = count + 1
    local wantedIndex = math.floor((step * i) + 0.5)
    print("wanted index " .. wantedIndex)
    if wantedIndex > tableLen then
        print("out of bounds!")
    end
end

local worked = n == count
print("did it match? " .. tostring(worked) .. " count " .. tostring(count))

这是 n=3 的输出

choosing 3 numbers
wanted index 0
wanted index 9
wanted index 18
wanted index 27
out of bounds!
did it match? false count 4

这里是 n=15

wanted index 0
wanted index 1
wanted index 3
wanted index 4
wanted index 5
wanted index 6
wanted index 8
wanted index 9
wanted index 10
wanted index 12
wanted index 13
wanted index 14
wanted index 15
wanted index 17
wanted index 18
wanted index 19
did it match? false count 16

标签: mathlua

解决方案


听起来你想要这样的东西?

local function evenly(number, items)
    local space = math.floor((#items-1) / (number-1))
    for i=1,#items,space do
        print(items[i])
    end
end

evenly(5, {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20})

推荐阅读