I want to achieve making a string.random function
It does not print all the characters but instead only 3 and then prints a copy
I want this but it happens randomly I want this to happen 100% of the time but random letters:

What it mostly does:

I have tried devform.roblox.com and youtube.com
I am trying to create my easy string functions but when I try it, it just prints 2 of the same word and only sometimes prints all of them. I want to make it print all of the ‘words’ such as:
Hello
I
Am
Freed
--or
Hello
Am
Freed
I
--instead of
Hello
I
Am(x2)
Sorry coudlnt add much detail
module.random = function(String)
local strsplit = String:split(" ")
local characters = {}
for i = 1,#strsplit do
table.insert(characters,strsplit[i])
print(characters[math.random(1,#characters)])
table.remove(characters,#strsplit[i])
end
end
1 Like
shuffle sounds like a better term for what you’re trying to do–so lets call it module.shuffle! Thankfully Fisher–Yates can help us do this!
module.shuffle = function(String)
local words = String:split(" ")
for i = #words, 2, -1 do
local j = math.random(i)
words[i], words[j] = words[j], words[i]
end
return words
end
We can iterate over the words array and for each iteration we pick a random number between i and 1 and we swap the element at words[i] and the element at words[j] with each other.
You would want to generate a random number between 1 and i because you don’t want to swap values that have already been swapped before.
You would also want to stop at 2 instead of 1 because at 2 it would just swap the last two elements–finishing the algorithm–but it actually does not matter since the last iteration will swap the same elemnt which itself if you end at index 1.
and so, an example:
local sentence = "the doom slayer is coming for your lasagna recipe"
local response = table.concat(module.shuffle(sentence), " ")
print(response)
your doom for the coming slayer recipe is lasagna
3 Likes