7

I am trying to generate 12 characters alphanumeric string in julia with the following snippets:
a)
an = randstring(rand(Bool) ? ('A':'Z') : ('0':'9'), 12)
b)

an = "" 
for i in [1:12]
    an *= randstring(rand(Bool) ? ('A':'Z') : ('0':'9'))
end

but both gives either complete 12 digits or 12 alphabets but not of their combination.

please guide me in generating combination of 12 alphanumeric string.

1
  • 2
    Be aware that for i in [1:12]means something completely different from for i in 1:12. Are you sure this was your intention? Commented Jun 5, 2019 at 6:29

1 Answer 1

11

If you don't mind using both upper and lower case letters, you can simply call randstring(12):

julia> using Random

julia> randstring(12)
"0IPrGg0JVONT"

julia> randstring(12)
"EB5dhw4LVno7"

If you want only uppercase letters (and numbers), then you need to pass randstring a collection that includes only uppercase letters and numbers, which you can achieve with ['A':'Z'; '0':'9']:

julia> randstring(['A':'Z'; '0':'9'], 12)
"ASZQAT5YX3OL"

julia> randstring(['A':'Z'; '0':'9'], 12)
"FEV5HTGMLQ6X"

Finally, note that you could provide the collection of characters as a string:

julia> randstring("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 12)
"ASZQAT5YX3OL"
Sign up to request clarification or add additional context in comments.

5 Comments

Random.seed!(0) inside the function returns the same random alphanumeric string!
Yeah, don't put Random.seed!(0) inside your function. I just used that so you can exactly reproduce the results shown in my answer.
@AVA, See en.wikipedia.org/wiki/Random_seed for an explanation of random seeds, in case you're not already aware.
I removed Random.seed!(0) from the examples since random number generation is not guaranteed to be stable across Julia versions anyways.
randstring('A':'Z', 2) works as well. Note that randstring(['A':'Z'], 2) without ; will give an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.