28 lines
708 B
Lua
28 lines
708 B
Lua
Utils = {}
|
|
|
|
--- Returns up to `n` random values from the given array. Will return fewer if `n > #fromArr`
|
|
---@generic T
|
|
---@param fromArr T[]
|
|
---@param n number
|
|
---@generic T[]
|
|
function Utils.getNDifferentValues(fromArr, n)
|
|
assert(n >= 0, "n must be a non-negative integer")
|
|
if n > #fromArr then
|
|
n = #fromArr
|
|
end
|
|
local found = 0
|
|
local indexes = {}
|
|
while found < n do
|
|
local randomIndex = math.random(#fromArr)
|
|
if not indexes[randomIndex] then
|
|
found = found + 1
|
|
indexes[randomIndex] = true
|
|
end
|
|
end
|
|
|
|
local randoms = {}
|
|
for i in pairs(indexes) do
|
|
randoms[#randoms + 1] = fromArr[i]
|
|
end
|
|
return randoms
|
|
end |