我创建了以下字符串操作函数,用于在Lua中随机设置我传递的字符串:
require "string"
require "math"
math.randomseed( os.time() )
function string.random( self )
local tTemporary, tNew = {}, {}
if not self or self:len() < 5 then
return nil
end
self:gsub( "%a", function( cChar )
table.insert( tTemporary, cChar )
end
)
for i = 1, #tTemporary, 1 do
local iRandom = math.random(1, #tTemporary)
tNew[i] = tTemporary[iRandom]
table.remove( tTemporary, iRandom )
end
return table.concat(tNew, " ")
end这能被优化/更随机化吗?
发布于 2013-05-04 03:32:24
有几点需要考虑:
shuffle而不是random将是一个更好的名称,因为这正是它所要做的。所以我会把你的原始代码重构成两个函数。这里有一种可能性:
function shuffle(self)
if type(self) ~= 'table' then return nil end
for i = #self, 2, -1 do
local randi = math.random(i)
self[i], self[randi] = self[randi], self[i]
end
return self
end
function shuffle_words(str)
local strtable = {}
for each in str:gmatch("%a+") do
table.insert(strtable, each)
end
return table.concat(shuffle(strtable), ' ')
endhttps://codereview.stackexchange.com/questions/24700
复制相似问题