How to make math random not repeat a number more than twice

So basically i want math random to only be able to pick it’s set of numbers not more than twice.

local Label = script.Parent

while true do
	wait(1)
	local Number = math.random(0,1)
	Label.Text = tostring(Number)
end

One solution may be to store the history of the last two numbers that were generated, then check to make sure a third, newly generated number is not the same as the first and second. You can think of these as boolean values (and perhaps they should be if you’re only going to use 0 and 1; this will need to be modified slightly if not)

local history = {}
for i = 1, 100 do -- Randomly generate 100 numbers [0, 1] and see there are never 3 in a row
	local num = math.random(0, 1) -- generate either 0 or 1
	-- The first two conditions "set up" the history that is used in the third condition - checking if the last two generated were a match
	if not history[1] then
		history[1] = num
	elseif not history[2] then
		history[2] = num
	elseif num == history[1] and num == history[2] then
		num = history[1] == 1 and 0 or 1 -- you *could* also just keep randomly generating random numbers until they don't match, but it's more efficient to force it in this case
		-- This can be modified if you ever want to relax or increase the requirements by changing the condition to check every element in the table, e.g., No matching numbers more than 10 times in a row. This is easier since there's only two elements we have to worry about
	end
	-- print(num) -- @@@ You can uncomment this to show it works in the output
	-- Shift the history down, getting rid of the first element: {0, 0} with a num of 1 becomes => {0, 1} 
	history[1] = history[2]
	history[2] = num
end

Try this:

local Label = script.Parent

local LastNum = nil

while true do

     wait(1)

     local Number = math.random(0,1)
	
     if Number ~= LastNum then
        
	     Label.Text = tostring(Number)

         LastNum = Number

     end

end

What this is doing is it’s checking of the last number generated is the same as the one that was just generated and if it’s not it runs.

the easiest solution would be to make it a function and it will end up looking like this:

local last = -1

local function generateRandomNumber(range1: number, range2: number)
	local currentNumber
	repeat
		currentNumber = math.random(range1, range2)
	until last ~= currentNumber
	last = currentNumber
	return currentNumber
end

while true do
	print(generateRandomNumber(1, 2))
	wait(0.5)
end
3 Likes