Trying to get a random 4-digit code for a locked door in my game but I want the password to have no repeating numbers. How would I do this?
Code:
1 | local startCode = game.ReplicatedStorage.startCode |
2 |
3 | local numb 1 = math.random( 0 , 9 ) |
4 | local numb 2 = math.random( 0 , 9 ) |
5 | local numb 3 = math.random( 0 , 9 ) |
6 | local numb 4 = math.random( 0 , 9 ) |
7 |
8 | startCode.Value = ( tostring (numb 1 ) .. tostring (numb 2 ) .. tostring (numb 3 ) .. tostring (numb 4 )) |
9 | print (startCode.Value) |
One way to do this is to make an array of digits from 0 to 9
1 | Digits = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } |
We take a random number from Digits, and then remove said number since so that it cannot appear again
1 | RandoNum = math.random( 1 , #Digits) |
2 | Chosen = Digits [ RandoNum ] |
3 | table.remove(Digits, RandoNum) |
Then we can just take said number and add it to startCode.Value
If you wanted your code to be in a loop, it would look something like this:
1 | Digits = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } |
2 | for i = 1 , 4 do |
3 | RandoNum = math.random( 1 , #Digits) |
4 | Chosen = Digits [ RandoNum ] |
5 | table.remove(Digits, RandoNum) |
6 | startCode.Value = startCode.Value.. tostring (Chosen) |
7 | end |
Start by making a array/table for every number in the number combo.
1 | local code = { "N" , "N" , "N" , "N" } |
Now, let's make a for loop for every part of the table. If there's no value set, ("N") we'll change it to a random number. Next let's make sure no other number in the array/table is that number.
01 | local function check() |
02 | for i, v in pairs (code) do |
03 | if v = = "N" then |
04 | return true |
05 | end |
06 | end |
07 | end |
08 | while check() do |
09 | for i, v in pairs (code) do |
10 | if v = = "N" then |
11 | local suggestednum = math.random( 0 , 9 ) |
12 | print (suggestednum) |
13 | local isnotothernumber = true |
14 | for i, v in pairs (code) do |
15 | if v = = suggestednum then |
So there you are! A randomly generated number sequence that is 4 digits long and 2 digits will never be the same.