如何使用lua随机排列单词的字母

时间:2018-08-08 17:31:15

标签: lua telegram-bot

我在PHP中使用了这个str_shuffle()函数 和梅卡this api 我需要做同样的想法,以字母之间的空格和lua来洗净字母  与电报机器人合作时,我搜索了很多东西,却没有发现类似的东西

3 个答案:

答案 0 :(得分:2)

以下是一些代码,您可以通过注释来做您想做的事情,以解释其工作原理:

function tablelength(table) -- to calculate the length of a table
  local count = 0
  for _ in pairs(table) do count = count + 1 end -- loop through each of its items and add to a counter
  return count
end

function stringtoletters(text) -- split a string into its individual characters
  local letters = {}
  for a = 1, string.len(text) do -- loop through each character in the string and add it to the table
    table.insert(letters, string.sub(text, a, a))
  end
  return letters
end

function randomlyreorganizetext(text) -- the function that actually does the stuff AKA the meat
  local letters = stringtoletters(text)
  local n = tablelength(letters)

  math.randomseed(os.time()) -- initialize the random number generator
  math.random(); math.random(); math.random() -- the first few numbers are apparently not very random so get rid of them

  for i=n,1,-1 do -- go through each character and switch it out with another one of the of the characters at random
    local j = math.floor(math.random() * (i-1)) + 1 -- decide which character to swap with
    local tmp = letters[i] -- make a backup of the current value
    letters[i] = letters[j] -- change to random characters value
    letters[j] = tmp -- put what used to be the current value into the random characters position
  end

  return table.concat(letters, " ") -- turn the table back into a string and put spaces between each element
end

print(randomlyreorganizetext("hello"))

答案 1 :(得分:1)

这是我的看法。第一个gsub按照字符串中的字母出现的顺序对其进行索引。然后,我们shuffle索引并使用经过改组的索引将字母与另一个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)

答案 2 :(得分:1)

math.randomseed(os.time())

local 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"))