mercredi 18 août 2021

Shuffle and unscramble a string (Lua)

I have a function to shuffle strings from another article adapted to reorder the characters with a table of predefined numbers. It works perfectly, so I also needed a function to unscramble this string using the number table, but I have no idea how to do this, especially after having tried and failed several times.

Shuffle function:

randomValues = {} 
for i = 1, 60 do
   table.insert(randomValues, 1, math.random())
end
function shuffle(str)
   math.randomseed(4)
   local letters = {}
   local idx = 0
   for letter in str:gmatch'.[\128-\191]*' do
      idx = idx + 1
      table.insert(letters, {letter = letter, rnd = randomValues[idx]})
   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

Any tips?




Aucun commentaire:

Enregistrer un commentaire