Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How to make 4 digit code have no repeating numbers?

Asked by 2 years ago

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:

1local startCode = game.ReplicatedStorage.startCode
2 
3local numb1 = math.random(0, 9)
4local numb2 = math.random(0, 9)
5local numb3 = math.random(0, 9)
6local numb4 = math.random(0, 9)
7 
8startCode.Value = (tostring(numb1) .. tostring(numb2) .. tostring(numb3) .. tostring(numb4))
9print(startCode.Value)

2 answers

Log in to vote
1
Answered by 2 years ago

One way to do this is to make an array of digits from 0 to 9

1Digits = {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

1RandoNum = math.random(1, #Digits)
2Chosen = Digits[RandoNum]
3table.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:

1Digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
2for 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)
7end
Ad
Log in to vote
0
Answered by 2 years ago

Start by making a array/table for every number in the number combo.

1local 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.

01local function check()
02 for i, v in pairs(code) do
03    if v == "N" then
04            return true
05        end
06end
07end
08while 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
View all 29 lines...

So there you are! A randomly generated number sequence that is 4 digits long and 2 digits will never be the same.

Answer this question