6

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.

AVA
  • 2,474
  • 2
  • 26
  • 41
  • 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? – DNF Jun 05 '19 at 06:29

1 Answers1

9

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"
Cameron Bieganek
  • 7,208
  • 1
  • 23
  • 40