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:

local startCode = game.ReplicatedStorage.startCode

local numb1 = math.random(0, 9)
local numb2 = math.random(0, 9)
local numb3 = math.random(0, 9)
local numb4 = math.random(0, 9)

startCode.Value = (tostring(numb1) .. tostring(numb2) .. tostring(numb3) .. tostring(numb4))
print(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

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

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

Digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
for i = 1, 4 do
    RandoNum = math.random(1, #Digits)
    Chosen = Digits[RandoNum]
    table.remove(Digits, RandoNum)
    startCode.Value = startCode.Value..tostring(Chosen)
end
Ad
Log in to vote
0
Answered by 2 years ago

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

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.


local function check() for i, v in pairs(code) do if v == "N" then return true end end end while check() do for i, v in pairs(code) do if v == "N" then local suggestednum = math.random(0,9) print(suggestednum) local isnotothernumber = true for i, v in pairs(code) do if v == suggestednum then isnotothernumber = false end end if isnotothernumber then code[i] = suggestednum end end end -- if you want it to be a string combostr = "" for i, v in pairs(code) do combostr = combostr..v end end

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