30
\$\begingroup\$

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)
\$\endgroup\$
  • 1
    \$\begingroup\$ Can we assume a maximum value for N? \$\endgroup\$ – JAD May 5 '17 at 14:11
  • \$\begingroup\$ Related. \$\endgroup\$ – a spaghetto May 5 '17 at 15:36

43 Answers 43

1
2
0
\$\begingroup\$

Python 3, 132 124 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!

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

Mathematica 66 Bytes

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

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

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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?

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ 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)"? \$\endgroup\$ – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ May 6 '17 at 15:10
  • \$\begingroup\$ It doesn't. This is what happens when you mix coding and alcohol ;) \$\endgroup\$ – Johan du Toit May 6 '17 at 15:23
  • \$\begingroup\$ This can random seg fault because it read memory possible do not own from the program \$\endgroup\$ – user58988 May 8 '17 at 8:17
  • \$\begingroup\$ 65 bytes \$\endgroup\$ – ceilingcat Jul 13 at 5:16
0
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You can save five bytes by replacing string.char with s.char. \$\endgroup\$ – Josh May 6 '17 at 18:41
  • \$\begingroup\$ @Josh while it is frustrating for people to not respond to your suggestions, edits are not for improving someone else's code. \$\endgroup\$ – Cyoce May 6 '17 at 19:36
  • \$\begingroup\$ @Josh Change made. Didn't actually know I could do that. Good to know for the future. Thanks. \$\endgroup\$ – Blab May 7 '17 at 4:54
  • \$\begingroup\$ 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. \$\endgroup\$ – Josh May 7 '17 at 12:03
0
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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]
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

C, 54 52 bytes

  • -2 bytes, thanks to @RosLuP

Try Online

i;f(n){n&&f(n-(isalnum(i=rand()%128)&&putchar(i)));}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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... \$\endgroup\$ – user58988 May 8 '17 at 7:26
0
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ 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)));}}. \$\endgroup\$ – Kevin Cruijssen May 5 '17 at 13:58
0
\$\begingroup\$

Ruby, 47 bytes

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

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

PHP, 51 bytes

while($argn-=ctype_alnum($c=chr(rand()))&&print$c);

Run as pipe with -nR or try it online.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ no longer valid \$\endgroup\$ – ASCII-only Jan 30 '19 at 6:08
  • \$\begingroup\$ @ASCII-only: Updated. \$\endgroup\$ – ბიმო Jan 31 '19 at 14:55
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.