如何使用 Lua 洗牌单词字母

我之前使用过 PHP 中的 str_shuffle() 函数,以及使用 这个 API 我需要使用 Lua 实现相同的功能,也就是在字母之间加上空格洗牌,以便于在 Telegram 机器人中使用。我搜索了很多但没有找到类似的实现方法。

点赞
用户5237091
用户5237091

以下是一些代码,可以按照注释说明执行:

function tablelength(table) -- 计算表的长度
  local count = 0
  for _ in pairs(table) do count = count + 1 end -- 循环每个项并添加到计数器中
  return count
end

function stringtoletters(text) -- 将字符串拆分为单个字符
  local letters = {}
  for a = 1, string.len(text) do -- 循环字符串中的每个字符并将其添加到表中
    table.insert(letters, string.sub(text, a, a))
  end
  return letters
end

function randomlyreorganizetext(text) -- 实际运作的函数,也就是核心部分
  local letters = stringtoletters(text)
  local n = tablelength(letters)

  math.randomseed(os.time()) -- 初始化随机数生成器
  math.random(); math.random(); math.random() -- 前几个数字不够随机,所以丢弃

  for i=n,1,-1 do -- 遍历每个字符并将其替换为另一个随机字符
    local j = math.floor(math.random() * (i-1)) + 1 -- 决定与哪个字符进行交换
    local tmp = letters[i] -- 备份当前值
    letters[i] = letters[j] -- 改为随机字符的值
    letters[j] = tmp -- 将原来的值放回到随机字符的位置
  end

  return table.concat(letters, " ") -- 将表转换回字符串,并在每个元素之间添加空格
end

print(randomlyreorganizetext("hello"))
2018-08-08 19:17:16
用户107090
用户107090

这是我的方法。第一个 gsub 函数按字母出现的顺序对字符串中的字母进行索引。然后,我们使用 洗牌算法 对索引进行随机排列,并使用排列后的索引重新映射字母。

s="How to shuffle the letters of a word using lua"
t={}
n=0

s:gsub("%a",function (c)
        if t[c]==nil then
            n=n+1
            t[n]=c
            t[c]=n
        end
    end)

math.randomseed(os.time())
for i=n,2,-1 do
    local j=math.random(i)
    t[i],t[j]=t[j],t[i]
end

z=s:gsub("%a",function (c) return t[t[c]] end)
print(s)
print(z)
2018-08-08 21:48:20
用户6834680
用户6834680
math.randomseed(os.time())

function shuffle(str)
   local letters = {}
   for letter in str:gmatch'.[\128-\191]*' do
      table.insert(letters, {letter = letter, rnd = math.random()})
   end
   table.sort(letters, function(a, b) return a.rnd < b.rnd end)
   for i, v in ipairs(letters) do letters[i] = v.letter end
   return table.concat(letters)
end

print(shuffle("How to shuffle the whole UTF-8 string"))
2018-08-09 07:51:57