# Generating a random alphanumeric string of length N

What is the shortest way of generating a random string with a given length and with only alphanumeric characters allowed?

• example of a random string: with N = 9 output would be aZua7I0Lk
• the given length N can be assumed to be always greater than 0
• if necessary you can assume 256 as a maximum value for N, but solutions with higher limits for N and still having a fast computation time are preferred
• allowed characters: 0-9, a-z and A-Z
• a character can occur more than once in the output string
• each possible string should be equally likely (to the accuracy of your language's random number generator)
• Can we assume a maximum value for N? – JAD May 5 '17 at 14:11
• Related. – a spaghetto May 5 '17 at 15:36

# Python 3, 132124 123 bytes

...I most probably can golf this further. Might be able to do that by using ASCII numbers. Tried and ended up longer than Java.

from random import*
a='abcdefghijklmnopqrstuvwxyz0123456789'
f=lambda n:''.join(choice(a+a[:-10].upper())for i in range(n))


Try it online!

• Here is an improved version based on an older revision (114 bytes) – ovs May 5 '17 at 15:14
• I had to downvote for a meme but you said it was fine :P – Christopher May 8 '17 at 0:27

## Mathematica 66 Bytes

""<>Cases[1~CharacterRange~122,_?LetterQ|_?DigitQ]~RandomChoice~#&


which is a little bit shorter than using the WordCharacter pattern with StringCases

## C, 67 Bytes

c;f(n){char b[1],*p=b+64;for(;n;)isalnum(c=*p++)?putchar(c),n--:0;}


Try it online

I'm getting some strange results - keep on hitting the run button - feels like I'm a character in Lost:

PoPPmyE79hmy
arcPaTasITJK
PCFaniHSAKPS
yPytyxQoAKMA
DOPrgDONeDO8
...


Can anyone explain why there is always a 'P' or 'p' in the output?

• How does this solution fulfill the last condition "each possible string should be equally likely (to the accuracy of your language's random number generator)"? – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ May 6 '17 at 15:10
• It doesn't. This is what happens when you mix coding and alcohol ;) – Johan du Toit May 6 '17 at 15:23
• This can random seg fault because it read memory possible do not own from the program – user58988 May 8 '17 at 8:17
• 65 bytes – ceilingcat Jul 13 '20 at 5:16

## CJam, 18 bytes

ri{;'],_el^9,+mR}%


Explanation:

ri   e# Read integer
{    e# For each (loops from 0..n-1):
;   e#   Delete the index from the top of the stack
'], e#   Get all the characters 0x00 to 0x5b ("[")
_el e#   Duplicate and convert letters to lowercase
^   e#   Symmetric set difference - this keeps only
e#     uppercase and lowercase letters
A,+ e#   Add all the digits into this string
mR  e#   Random choice of one element in the array
}%   e# End for loop
e# Implicit output


# Lua, 105 98 bytes

s,n="",io.read()while#s<n do c=s.char(math.random(48,122))s=s..(c:match"%w"and c or'')end print(s)


Generate any character between 48 and 122, if alphanumeric, add to output string. When output string is length n, stop and output.

Edit: Saved 7 bytes thanks to suggestions from Josh.

• You can save five bytes by replacing string.char with s.char. – Josh May 6 '17 at 18:41
• @Josh while it is frustrating for people to not respond to your suggestions, edits are not for improving someone else's code. – Cyoce May 6 '17 at 19:36
• @Josh Change made. Didn't actually know I could do that. Good to know for the future. Thanks. – Blab May 7 '17 at 4:54
• You can also replace c:match("%w") with c:match"%w" for another two bytes saved. s refers to your empty string variable by the way, it cannot always be used. – Josh May 7 '17 at 12:03

## Clojure, 80 bytes

#(apply str(for[i(range %)](char(rand-nth(mapcat range[48 97 65][57 122 90])))))


I guess the only smart part is building that set of ASCII integer values.

# Axiom, 150 bytes

f(x:NNI):Union(String,Complex INT)==(x>9.E8=>%i;c:=alphanumeric()::String;r:="";repeat(x=0=>break;x:=x-1;w:=1+random()@INT rem 62;r:=concat(c.w,r));r)


i find repeat( ...break...) the most versatile type of loop in Axiom as for(;;) in C. I find functions without some think or reflection on their input only danger toys

   [0,""]
[1,"t"]
[2,"rT"]
[10,"fcCOgd2aoP"]
[100,
"byFH5ikoQTIEA3TdJ4thNueA0vuowxz5PC7N1yUEgZUkuddjfwbRjYMim1mAYzLhZ8hDJskOUZ
SckbflbU1ZL2q0KTWUMF9dx6jX"
]
[10000000000000000,%i]


# C, 54 52 bytes

• -2 bytes, thanks to @RosLuP

Try Online

i;f(n){n&&f(n-(isalnum(i=rand()%128)&&putchar(i)));}

• Why not C: i;f(n){n&&f(n-(isalnum(i=rand()%128)&&putchar(i)));} but this can seg fault the program in case of input too much long... – user58988 May 8 '17 at 7:26

# C#, 214 177 bytes

Sorry to embarrass myself like this but:

void q(){int k=int.Parse(Console.ReadLine());Random r=new Random();for(;k>0;k--){Console.Write((char)(r.Next(1,4)>2?r.Next(1,3)>1?r.Next(97,123):r.Next(48,58):r.Next(65,91)));}}}}


Shaved some bytes off due to suggestion to just make it a function.

• Hi, welcome to PPCG! The default on PPCG is program or function, unless other specified by OP. Since this isn't the case, you can remove the namespace System{class P{static void Main(){int k=int.Parse(Console.ReadLine());...}}} part, and use a method (i.e. void f(int k){...}) instead. So it becomes void f(int k){Random r=new Random();for(;k>0;k--){Console.Write((char)(r.Next(1,4)>2?r.Next(1,3)>1?r.Next(97,123):r.Next(48,58):r.Next(65,91)));}}. – Kevin Cruijssen May 5 '17 at 13:58

# Ruby, 47 bytes

->n{([*?a..?z,*?A..?Z,*?0..?9]*n).sample(n)*''}


Try it online!

# APL NARS, 65 bytes, 35 chars

{(⍵≤0)∨⍵≥1E6:''⋄t[?¨⍵⍴⍴t←⎕A,⎕a,⎕D]}


As usual here do not is specificied the range of validity for the function... I agree in check for range but not agree 100% in checking the type, because some time is possible one extention for one function (possible not in this case). Test:

  g←{(⍵≤0)∨⍵≥1E6:''⋄t[?¨⍵⍴⍴t←⎕A,⎕a,⎕D]}
g ¯2000000

g 0

g ¯3

g 23
86uSfWH1zfpj4JE439he9Jp
g 3
ueQ
g 2
l3
g 1
M
g 100
pkHi07YmFmZpr9TpUNCIEtQf20CURGszkP2LvzgpnfaZTKPg3nYvo4PK0Rg
1cMxcjSRGWLrtf1RP8NEC3HlIcjW6TqfSOdqmrSqu


# PHP, 51 bytes

while($argn-=ctype_alnum($c=chr(rand()))&&print$c);  Run as pipe with -nR or try it online. # Alchemist, 577 689 bytes Contains a line for every character [0-9A-Za-z]: _->In_n n->Out_"0" ... n->Out_"9" n->Out_"A" ... n->Out_"Z" n->Out_"a" ... n->Out_"z"  Input from stdin, try it online! ## Explanation The universe of Alchemist will start with one _-atom, so the only thing that can happen is to read the number of n-atoms. Then one of the remaining rules will be matched pseudo-uniformly at random until no n-atoms remain. • no longer valid – ASCII-only Jan 30 '19 at 6:08 • @ASCII-only: Updated. – ბიმო Jan 31 '19 at 14:55 • So much for code-golf... :P – Makonede Feb 19 at 23:24 # 05AB1E, 4 bytes žKãΩ  Try it online! Times out on TIO for inputs $$\>3\$$, but it does work in theory. žKãΩ # full program Ω # random element from... žK # "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"... ã # to the cartesian power of... # implicit input # implicit output  # Alternative, 4 bytes žLãΩ  Try it online! žLãΩ # full program Ω # random element from... žL # "zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA9876543210"... ã # to the cartesian power of... # implicit input # implicit output  # Zsh, 33 bytes tr -dc a-zA-Z0-9</*/ur*|head -c$1


Try it online!

# Javascript, 83 bytes

f=n=>n?f(--n)+String.fromCharCode((k=Math.random()*62|0)+(k<10?48:(k<36?87:29))):''


Explained:

f=n=>  //Define function, n =  string length
n?      // if n is not falsy (0)
f(--n)+ //return f(n-1) (1 char shorter) plus
String.fromCharCode( // the character of
(k=Math.random()*62|0) //random number between 0 and 62 (num of chars)
+(
k<10?          //plus, if k < 10 (char is number)
48             //k + 48
:(k<36?        //else, if k < 36 (char is lowercase)
87             //k + 87
:29)           // else k + 29
)
)
:''   //if n is falsy, return empty string.


The numbers (48,29,etc) come from lining the charcodes up: |char|num|charcode|num - charcode| | - | - | - | - | | 0 | 0 | 48 | 48 | | 1 | 1 | 49 | 48 | | ... | ... | ... | ... | | 9 | 9 | 57 | 48 |

So random + 48 for numbers. For lowercase,

char num charcode num - charcode
a 10 97 87
b 11 98 87
... ... ... ...
z 35 122 87

so rand + 87, and for uppercase, |char|num|charcode|num - charcode| | - | - | - | - | | A | 36 | 65 | 29 | | B | 37 | 66 | 29 | | ... | ... | ... | ... | | Z | 61 | 90 | 29 |

# PowerShell, 56 bytes

param($n)-join((0..9+'a'..'z'+'A'..'Z')*$n|random -C \$n)


Try it online!