How to randomize letters in a string?

I’m currently working on a system where you guess the code from a given gibberish letters then you put it inside a textbox like this

HANK turns to HNKA

I would go into the string api reference on the dev page. There’s prob something there. If you seperate the middle characters after a character count it should work.

There might be an easier way of doing it, but you could convert the string into a table letter by letter. It would be relatively easy to randomise the table positions and then convert it back into string form.

If you needed help converting the string into a table:

2 Likes

There is a way to format so that a string will be inserted in a string. . However the way I would go is to generate a random number between 1 to the length of the string then simply index a character of the table then convert the table into a string. Then you can simply do that for each character of the string

You might want to look into string.gsub, string.format and string.split as functions you may consider using for the code

Agreed with @PerilousPanther. But would suggest you use https://developer.roblox.com/en-us/api-reference/lua-docs/utf8 to build a table.

You can shuffle that table with this function: A simple array shuffle function for Lua implementing the Fisher-Yates shuffle. · GitHub

2 Likes
-- example string
local Sentence = "Hello world!"

-- shuffle function mike linked
local function ShuffleTable(Table)
	local j
	for i = #Table, 2, -1 do
		j = math.random(i)
		Table[i], Table[j] = Table[j], Table[i]
	end
end

local function Randomize(String)
	-- split string into an array of words {"Hello", "world!"}
	local Words = String:split(" ")
	
	for i, Word in ipairs(Words) do
		-- split each word into letters {"H", "e", "l", "l", "o"}, {"w", "o", "r", "l", "d", "!"}
		local Letters = Word:split("")
		ShuffleTable(Letters)
		-- concatenate randomized array of letters back into a string
		Words[i] = table.concat(Letters, "")
	end
	
	-- concatenate the array of words back into a string
	return table.concat(Words, " ")
end

for i = 1, 20 do
	print(Randomize(Sentence))
end
> leHlo dol!rw
> lloeH owlr!d
> lHloe rlwdo!
> oellH oldw!r
> lHoel orw!ld
> oellH or!lwd
> eoHll !wdolr
> Holel d!lrwo
> loeHl wodrl!
> eHlol !dolwr
> lleoH wldr!o
> oHlel dlowr!
> lloeH rdo!wl
> eHlol rowld!
> olHle wdr!ol
> eHoll !ldowr
> lHelo lw!dro
> lloHe dlo!wr
> Holel o!drwl
> loelH w!olrd

The script doesn’t actually need to be so long as you guys are making it

local t = {text:sub(1,1)}
for i = 2, #text do
    table.insert(t, text:sub(i,i), math.random(#t+1)
end
local s = table.concat(t)
2 Likes

I managed to combine the code from the forums and it works as intended

local function shuffle(str)
	local t = {}
	for i = 1, #str do
		t[i] = str:sub(i, i)
	end
	for i = #t, 2, -1 do
		local j = math.random(i)
		t[i], t[j] = t[j], t[i]
	end
	return table.concat(t)
end

print(shuffle("insert string here"))
6 Likes