Ozzypig

Scramble Words in Paragraph (Lua)

Dec 4th, 2016
109
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local function scrambleString(str)
  2.     -- Return a scrambled version of str
  3.     -- using Fisher-Yates shuffle
  4.     local result = ""
  5.     while str:len() > 0 do
  6.         local i = math.random(1, str:len())
  7.         result = result .. str:sub(i, i)
  8.         str = str:sub(1, i - 1) .. str:sub(i + 1)
  9.     end
  10.     return result
  11. end
  12.  
  13. local function scrambleWords(str)
  14.     return str:gsub("(%w+)", function (word)
  15.         if word:len() > 3 then
  16.             local middle
  17.             repeat
  18.                 -- Scramble the middle until it's not the same as the original middle
  19.                 middle = scrambleString(word:sub(2, word:len() - 1))
  20.             until middle ~= word:sub(2, word:len() - 1)
  21.             return
  22.                 word:sub(1, 1)
  23.                 .. middle
  24.                 .. word:sub(word:len())
  25.         else
  26.             -- Words 1, 2 or 3 letters long canot be scrambled
  27.             return word
  28.         end
  29.     end)
  30. end
  31.  
  32. print(scrambleWords([[
  33. When Derek was three, he received his first
  34. pair of pyjama bottoms. When he was five,
  35. he loudly decreed that he would never take
  36. them off. When he reached eight, his parents
  37. realized that Derek wasn't lying. At twelve
  38. he was bullied; at fifteen ignored; at
  39. seventeen, briefly, Derek became a fashion
  40. icon. Now Derek works at home, and his pyjama
  41. bottoms work with him. Theirs is the healthiest
  42. relationship Derek will ever have.]]))
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×