Module:Random: Difference between revisions

Content deleted Content added
m Protected Module:Random: High-risk Lua module ([Edit=Allow only autoconfirmed users] (indefinite) [Move=Allow only autoconfirmed users] (indefinite))
add limit parameter for lists, and optimise the p.item code slightly
Line 154:
--------------------------------------------------------------------------------------
 
function p.randomizeArray(t, limit)
-- Randomizes an array. It works by iterating through the list backwards, each time swapping the entry
-- "i" with a random entry. Courtesy of Xinhuan at http://forums.wowace.com/showthread.php?p=279756
-- If the limit parameter is set, the array is shortened to that many elements after being randomized.
-- The lowest possible value is 0, and the highest possible is the length of the array.
setRandomSeed()
forlocal ilen = #t, 2, -1 do
for i = len, 2, -1 do
local r = math.random(i)
t[i], t[r] = t[r], t[i]
end
if limit and limit < len then
return t
local ret = {}
for i, v in ipairs(t) do
if i > limit then
break
end
ret[i] = v
end
return ret
else
return t
end
end
 
Line 198 ⟶ 212:
local function makeRandomList(args)
local list = removeBlanks(args)
list = p.randomizeArray(list, tonumber(args.limit))
return list
end
Line 206 ⟶ 220:
setRandomSeed()
local list = removeBlanks(args)
iflocal #listlen >= 1 then#list
if len >= 1 then
return list[math.random(#listlen)]
end
end