PtokaX forum

Development Section => HOW-TO's => Topic started by: bastya_elvtars on 03 January, 2005, 09:20:38

Title: Mixing a string
Post by: bastya_elvtars on 03 January, 2005, 09:20:38
It randomises the chars in a string. Enjoy! :D


function mix(string)
local arr={} -- creates an array
local msg="" -- creates an empty strin
-- for a=1,strlen(string) do -- inserts every element of the string into the array
-- tinsert (arr,(strsub(string,a,a)))
-- end
gsub(string,"(.)",function (lett) -- it grabs every character of the string...
tinsert (%arr, lett) -- and inserts into the table
end)
repeat -- starts a loop
local n = random(getn(arr)) -- creates a random number between 1 and the array size
msg=msg..arr[n] -- merges the letter with the number in the array
tremove(arr,n) -- removes that letter from the array
until getn (arr)==0 -- loop stops when array is empty
return msg
end
Title:
Post by: chill on 05 January, 2005, 20:18:06
I like this code from rabid-wombat better,
in the end it is faster, cause when you have large strings,
table.remove will reindex  all other elements, and this will
take up some time when you for exsample, remove the
first entrie.
but I once made some tests with gfind and strsub,
depending on what you need, strsub can be faster,
since gfind gsub do the same,  they just come in handier

function JumbleString(str)
local tStr = { n = 0; };
local newString = "";

for char in string.gfind(str, "(.)") do
table.insert(tStr, char)
end

math.randomseed(os.clock());

-- Fisher-Yates shuffle
for n = table.getn(tStr), 1, -1 do
local pos = math.random(n);
newString = tStr[pos].." "..newString;
tStr[pos] = tStr[n];
end

return newString;
end

I wonder why Rabid never posted this....