More efficient way to make math.random not pick the same twice in a row?

Is there a more efficient way to make math.random not choose the same animation two times in a row than this?

local PunchedAnimations = {PunchedAni1, PunchedAni2, PunchedAni3, PunchedAni4}

local Picked = false
local OldAnimation
local NewAnimation

Picked = false
					
while not Picked do
if OldAnimation == nil then				
     OldAnimation = PunchedAnimations[math.random(1, #PunchedAnimations)]					 
     Picked = true
end

NewAnimation = PunchedAnimations[math.random(1, #PunchedAnimations)]
						
if OldAnimation ~= NewAnimation then
      Picked = true -- Stops the while loop
      OldAnimation = NewAnimation
end
wait()
end

First you make a function to return a random number

Make a variable to cache the result if it’s the same then call that function again within itself or else then return result

2 Likes

Could you give me an example?

This is another way I’ve done it with repeat now:

local OldAnimation

if OldAnimation == nil then
OldAnimation = PunchedAnimations[math.random(1, #PunchedAnimations)]
end
					
local NewAnimation
repeat 
NewAnimation = PunchedAnimations[math.random(1, #PunchedAnimations)]				
until NewAnimation ~= OldAnimation
					
OldAnimation = NewAnimation
Punched = Humanoid:LoadAnimation(NewAnimation)
Punched:Play()
print(NewAnimation)
1 Like

I made the exact same thing, but with a function as you suggested. There’s no difference haha

local function GetRandomNumber(Amount)
     return math.random(Amount)
end

local OldAnimation = PunchedAni1

local NewAnimation
repeat 
NewAnimation = PunchedAnimations[GetRandomNumber(#PunchedAnimations)]
						
until OldAnimation ~= NewAnimation
OldAnimation = NewAnimation
					
Punched = Humanoid:LoadAnimation(NewAnimation)
Punched:Play()
print(NewAnimation)

Ruizu is suggesting that you hold the previous random number as a variable, not the previous anim. So you compare the numbers without having to index the anim each time you check. This is more efficient like you asked, but the system in general is the same and pretty much as efficient as you are going to get.

4 Likes

Oh I see. Yeah alright, I’ll change it to hold the number instead of the animation. Thanks :smiley:
I didn’t completely understand what he said, so I’ll give you the solution instead haha

2 Likes