Excluded number for math.random()

This is a simple question:

How do you exclude a number in math random if the code was like this:

local randomNumber = math.random(2,15)

You can do it like this by writing some DIY code ( this won’t have an even distribution over the short term though )…

-- Excludes numbers 6 .. 9 -- local function getSparseRandom() local numbers = { 2,3,4,5,10,11,12,15 } return numbers[math.random(1,#numbers)] end -- .... Then later print(getSparseRandom()) print(getSparseRandom()) print(getSparseRandom()) print(getSparseRandom()) -- Again.. This probably won't be evenly distributed.

or you can use an SSK2 shuffle bag for a completely random and even distribution:

local bag = ssk.shuffleBag.new( 2,3,4,5,10,11,12,15 ) bag:shuffle( ) -- .. Then later just pull from the bag: print(bag:get()) print(bag:get()) print(bag:get()) print(bag:get()) -- .. Pulls random number from bag till empty, -- then re-fills bag with original contents -- then shuffles ... ad infinitum

Or just dont accept the result you dont want by doing a while…do loop

Hello,

or write direcly the list of numbers you want to exclude and then make a new list of numbers without them.

local exclude={1,5,9} local function search(n) local new={} for i=1,n do if not table.indexOf( exclude, i ) then new[1+#new]=i end end if #new==0 then print("too much exclusions") return end return new[math.random(#new)] end print( search(20) )

You can do it like this by writing some DIY code ( this won’t have an even distribution over the short term though )…

-- Excludes numbers 6 .. 9 -- local function getSparseRandom() local numbers = { 2,3,4,5,10,11,12,15 } return numbers[math.random(1,#numbers)] end -- .... Then later print(getSparseRandom()) print(getSparseRandom()) print(getSparseRandom()) print(getSparseRandom()) -- Again.. This probably won't be evenly distributed.

or you can use an SSK2 shuffle bag for a completely random and even distribution:

local bag = ssk.shuffleBag.new( 2,3,4,5,10,11,12,15 ) bag:shuffle( ) -- .. Then later just pull from the bag: print(bag:get()) print(bag:get()) print(bag:get()) print(bag:get()) -- .. Pulls random number from bag till empty, -- then re-fills bag with original contents -- then shuffles ... ad infinitum

Or just dont accept the result you dont want by doing a while…do loop

Hello,

or write direcly the list of numbers you want to exclude and then make a new list of numbers without them.

local exclude={1,5,9} local function search(n) local new={} for i=1,n do if not table.indexOf( exclude, i ) then new[1+#new]=i end end if #new==0 then print("too much exclusions") return end return new[math.random(#new)] end print( search(20) )