Module:Sandbox/trappist the monk/random sort
Appearance
require('strict');
local content = mw.title.getCurrentTitle():getContent() or ''; -- get the content of the list page
--[[--------------------------< R A N D O M _ S O R T >--------------------------------------------------------
swaps two members of a sequence table. One member is indexed sequentially (starting at [1]), the other index
is randomly selected.
]]
local function random_sort (frame)
local source = setmetatable({}, {__index = table})
local r_idx;
for article in content:gmatch ('([^\r\n] )[\r\n] ') do -- get an article title
if not (
article:match ('<!%-%-') or -- skip any line that has opening comment
article:match ('%-%->') or -- skip any line that has closing comment
article:match ('{{') or -- skip the line that holds the {{#invoke:}} for this function
'' == article) then -- skip these -- skip empty lines
source:insert (article); -- all others, add to the list
end
end
math.randomseed (os.time()); -- init random number generator with current timestamp
for i, v in ipairs (source) do
r_idx = math.random (i, #source) -- random index between i and length of source{} ([[Fisher–Yates shuffle]] per Anomie at my talk page)
if i ~= r_idx then -- if i and r_idx happen to be the same, don't bother swapping this article title with itself
source[i], source[r_idx] = source[r_idx], source[i]; -- swap article titles source[i] and source[r_idx]
end
end
return table.concat ({'count = ', #source, '<br />',
frame:callParserFunction ('#tag:syntaxhighlight', source:concat ('\n'))});
end
--[[--------------------------< E X P O R T E D F U N C T I O N----------------------------------------------
]]
return {
random_sort = random_sort
}