If you don’t understand my issue, I’ll give you some more context:
Basically, I have a disaster selector system, and it works, but when I ask it to select random disasters for x amount of times, sometimes the system chooses duplicate disasters from the table.
E.g.
OUTPUT – What I want it to be like:
fire
crumble
bomb
ufo
What’s actually happening:
ufo (x2)
crumble (x2)
Any solutions?
Relevant code:
game.ServerStorage.DisasterEvent.Event:Connect(function(number, bool)
local tbl_disasters = {"GearThem", "UFO", "Bomb", "FIRE", "Crumble", "meteorite"}
local chosenDisasters = {}
local chosen
for i = 1, number do
chosen = tbl_disasters[math.random(1, #tbl_disasters)]
table.insert(chosenDisasters, #chosenDisasters+1, chosen)
end
for _, v in pairs(chosenDisasters) do
print(string.lower(chosen))
end
while bool do
while wait(4) do
for i, v in pairs(chosenDisasters) do
if v == "GearThem" then
GearThem()
elseif v == "UFO" then
UFO()
elseif v == "FIRE" then
FIRE()
elseif v == "Bomb" then
Bomb()
elseif v == "Crumble" then
Crumble()
elseif v == "meteorite" then
meteorite()
end
end
end
end
end)
Maybe add a value in every disaster and once the disaster is chosen make that value true, and then check, if that value is true then that disaster exists…
The disasters are strings, so I can’t add a bool value in them. Unless you mean I make a table system with each disaster (being a table) storing these values in them
Hello there!
At first place I have noticed that you are actually printing the last chosen disaster.
So I would change this to:
print(string.lower(v))
And now I will actually get to the duplicated. You can stop this by checking if the disaster has been already chosen. You can achieve this by changing this line of your code
to this:
repeat chosen = tbl_disasters[math.random(1, #tbl_disasters)] until not table.find(tbl_disasters, chosen)
This should work. If it doesn’t, then get back to us!
local disasters = {
"GearThem",
"UFO",
"Bomb",
"FIRE",
"Crumble",
"meteorite"
}
local numOfDisasters = #disasters
local function chooseDisasters(howManyToChoose)
local chosenDisasters = table.create(howManyToChoose)
for i = 1, howManyToChoose do
local chosenIndex = math.random(i, numOfDisasters)
local chosenDisaster = disasters[chosenIndex]
disasters[i], disasters[chosenIndex] = chosenDisaster, disasters[i]
chosenDisasters[i] = chosenDisaster
end
return chosenDisasters
end