math - 从 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
解决方案
听起来你想要这样的东西?
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})
推荐阅读
- python - python中的频率分析程序
- java - 将旧版 PostgreSQL 导入 Hibernate 项目
- angular - 在 ngOnInit 中包含 self 方法后无法访问类中的函数
- ios - 为 Swift 格式化 NSArray
- sql - SQL从具有两个日期的行创建具有季度末日期的行
- c++ - Boost.Beast:是否可以构造一个 HTTP 批处理请求?
- python - 'rasa' 不是内部或外部命令、可运行程序或批处理文件
- python - 是否可以仅在列表中显示时简化 __repr__ 显示?
- reactjs - React Native Release apk 在访问相机视图时失败
- mysql - 在 `__in` 中的列表中包含一项的查询非常慢。否则,超级快