For example, lets say I want to pull a number from 1 - 10. That would be:
1 | math.random( 1 , 10 ) |
However, how would I be able to randomize a number from 1 - 10 but exclude a specific number, like 5?
make a blacklist that contains the numbers that you want to exclude, then iterate through the blacklist to check the random number
01 | local randomNumber = math.random( 1 , 10 ) |
02 | local blacklist = { 5 , 7 , 3 } -- put numbers to exclude here |
03 |
04 | local fails = { } |
05 | local good = false |
06 | local oof = false |
07 |
08 | repeat |
09 | for x = key,number in pairs (blacklist) do |
10 | if randomNumber = = number then -- if the random number is in blacklist |
11 | table.insert(fails, false ) |
12 | continue |
13 | end |
14 |
15 | if not randomNumber = = number then -- if the random number is not in blacklist |
Don't accept this answer.
1 | local math = setmetatable ( { } , { __index = math } ); |
2 |
3 | function math.random(a,b, blacklist) |
4 | local randomInt = getmetatable (math).__index.random(a,b); |
5 | if not (table.find(blacklist, randomInt)) then |
6 | return randomInt; |
7 | end |
8 | return math.random(a,b, blacklist) |
9 | end |
Not to be used in excessiveness, like all random functions. Not performant either, but Jiramide will probably come and fix it for me. This is a better alternative to ProjectInfiniti's answer, so please accept his answer. He had the right idea and the right execution.
people are putting wayyy to complicated stuff
01 | local function check(tbl, thing) |
02 | for _, v in pairs (tbl) do |
03 | if thing = = v then |
04 | return true |
05 | end |
06 | end |
07 | end |
08 | local function randomwithexclude(start, end , excluded) |
09 | local timesdone = 0 |
10 | local num |
11 | repeat |
12 | num = math.random(start, end ) |
13 | timesdone = timesdone + 1 |
14 | until check(excluded, num) ~ = true or timesdone = = 500 -- returns nil if the function runs 500 times |
15 | if timesdone = = 200 then |
not way too sure if it works. u could replace the timesdone with something else
Hi!
People are creating really complicated answers! I have two very simple solutions:
Solution 1: Reroll Until Not 5
01 | local chosenNumber = math.random( 1 , 10 ) |
02 |
03 | while true do |
04 | if chosenNumber = = 5 then |
05 | chosenNumber = math.random( 1 , 10 ) |
06 | else |
07 | break |
08 | end |
09 | wait() |
10 | end |
This simply chooses a number between 1 and 10. If the result is 5, it will keep on rerolling until it is not 5. Once the variable "chosenNumber" is not 5, the while loop will break.
Solution 2: Random From Table
1 | local avaliableNumbers = { 1 , 2 , 3 , 4 , 6 , 7 , 8 , 9 , 10 } |
2 | local chosenNumber = avaliableNumbers [ math.random( 1 , #avaliableNumbers) ] |
avaliableNumbers
is a table that has the numbers 1-10 except for 5.
Line 2 chooses a random value from the table.