Generating a random alphanumeric string of length N

30

5

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)

m13r

Posted 2017-05-05T09:05:16.883

Reputation: 405

1Can we assume a maximum value for N? – JAD – 2017-05-05T14:11:44.897

Related. – a spaghetto – 2017-05-05T15:36:44.903

Answers

4

Jelly, 4 bytes

ØBṗX

Try it online!

Explanation

ØBṗX
ØB     All letters (uppercase and lowercase) and digits
  ṗ    Cartesian power with {the input}
   X   Select a random possibility

Cartesian power basically generates all list of a given length that can be formed out of a given set of elements; that's exactly what we need here.

user62131

Posted 2017-05-05T09:05:16.883

Reputation:

If there are UTF-8 characters involved could that be really just 4 bytes? One UTF-8 character could be more than just one byte... – m13r – 2017-06-28T10:34:59.640

@m13r Jelly uses its own code page where these are all single byte characters – FlipTack – 2017-12-05T23:09:02.873

13

Taxi, 2577 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 l 1 l 1 r.[a]Go to Heisenberg's:n 1 r 1 r 3 r.Pickup a passenger going to Cyclone.Go to Go More:n 1 l 3 l 3 l.Go to Starchild Numerology:e 2 r.62 is waiting at Starchild Numerology.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 2 r.Pickup a passenger going to What's The Difference.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:n 2 r 2 r 1 r.Pickup a passenger going to Trunkers.Go to Trunkers:e 1 r 3 r 1 l.Pickup a passenger going to Multiplication Station.Go to Cyclone:w 2 r.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 2 l 1 r 3 l.Pickup a passenger going to Addition Alley.Go to Starchild Numerology:e 1 r 3 l 2 r.1 is waiting at Starchild Numerology.63 is waiting at Starchild Numerology.Pickup a passenger going to Addition Alley.Pickup a passenger going to The Underground.Go to Addition Alley:e 1 l 2 r 3 r 1 r.Pickup a passenger going to Joyless Park.Go to Writer's Depot:n 1 l 1 l.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789- is waiting at Writer's Depot.Pickup a passenger going to Chop Suey.Go to Joyless Park:n 3 r 2 r 2 l.Go to Chop Suey:w 1 r 1 r 1 l.[b]Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 1 l 1 r 1 l.Go to The Underground:e 1 r.Switch to plan "c" if no one is waiting.Pickup a passenger going to The Underground.Go to Fueler Up:s.Go to Chop Suey:n 3 r 1 l.Switch to plan "b".[c]Go to Joyless Park:n 1 r.Pickup a passenger going to The Underground.Go to Narrow Path Park:w 1 r 3 l.[d]Pickup a passenger going to KonKat's.Go to KonKat's:e 1 r.Pickup a passenger going to KonKat's.Go to The Underground:s.Switch to plan "e" if no one is waiting.Pickup a passenger going to The Underground.Go to Fueler Up:s.Go to Narrow Path Park:n 4 l.Switch to plan "d".[e]Go to KonKat's:n.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:n 1 l.Go to Narrow Path Park:e 1 l 1 r.Pickup a passenger going to Post Office.Go to Post Office:e 1 r 4 r 1 l.Go to Sunny Skies Park:s 1 r 1 l 1 r.Pickup a passenger going to The Underground.Go to The Underground:n 1 r 1 r 2 r.Switch to plan "f" if no one is waiting.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 3 l 2 l 1 l.Switch to plan "a".[f]

Try it online!

Taxi is super not made for this but you can do it! I'll try to explain what's happening below the un-golfed version.

Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park: north 1st left 1st left 1st right.
[a]
Go to Heisenberg's: north 1st right 1st right 3rd right.
Pickup a passenger going to Cyclone.
Go to Go More: north 1st left 3rd left 3rd left.
Go to Starchild Numerology: east 2nd right.
62 is waiting at Starchild Numerology.
Pickup a passenger going to Cyclone.
Go to Cyclone: east 1st left 2nd right.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to Divide and Conquer.
Pickup a passenger going to Divide and Conquer.
Go to Divide and Conquer: north 2nd right 2nd right 1st right.
Pickup a passenger going to Trunkers.
Go to Trunkers: east 1st right 3rd right 1st left.
Pickup a passenger going to Multiplication Station.
Go to Cyclone: west 2nd right.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: south 1st left 2nd right 4th left.
Pickup a passenger going to What's The Difference.
Go to What's The Difference: north 2nd left 1st right 3rd left.
Pickup a passenger going to Addition Alley.
Go to Starchild Numerology: east 1st right 3rd left 2nd right.
1 is waiting at Starchild Numerology.
63 is waiting at Starchild Numerology.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to The Underground.
Go to Addition Alley: east 1st left 2nd right 3rd right 1st right.
Pickup a passenger going to Joyless Park.
Go to Writer's Depot: north 1st left 1st left.
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789- is waiting at Writer's Depot.
Pickup a passenger going to Chop Suey.
Go to Joyless Park: north 3rd right 2nd right 2nd left.
Go to Chop Suey: west 1st right 1st right 1st left.
[b]
Pickup a passenger going to Narrow Path Park.
Go to Narrow Path Park: north 1st left 1st right 1st left.
Go to The Underground: east 1st right.
Switch to plan "c" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Fueler Up: south.
Go to Chop Suey: north 3rd right 1st left.
Switch to plan "b".
[c]
Go to Joyless Park: north 1st right.
Pickup a passenger going to The Underground.
Go to Narrow Path Park: west 1st right 3rd left.
[d]
Pickup a passenger going to KonKat's.
Go to KonKat's: east 1st right.
Pickup a passenger going to KonKat's.
Go to The Underground: south.
Switch to plan "e" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Fueler Up: south.
Go to Narrow Path Park: north 4th left.
Switch to plan "d".
[e]
Go to KonKat's: north.
Pickup a passenger going to Riverview Bridge.
Go to Riverview Bridge: north 1st left.
Go to Narrow Path Park: east 1st left 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: east 1st right 4th right 1st left.
Go to Sunny Skies Park: south 1st right 1st left 1st right.
Pickup a passenger going to The Underground.
Go to The Underground: north 1st right 1st right 2nd right.
Switch to plan "f" if no one is waiting.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park: north 3rd left 2nd left 1st left.
Switch to plan "a".
[f]

Start: Get stdin
Pick up the stdin value as text, convert it to a number, and go stick it somewhere to wait.

Plan A Part 1: Get a random integer 1-62
Get a random integer and then get 62 as a number. Duplicate both the random integer and the 62 because we'll need them later. You can only carry 3 passengers at once so we end up with rand, rand, and 62. (The other 62 will wait around until we get back.) Go divide rand by 62 and truncate the result to get an integer. Go back to get the other copy of 62 and multiply it by the truncated integer from the division. Finally, subtract the product from the first copy of rand. This gives us a number 0-61. Now we have to go back to pickup a 1 and add it to the result to get a number 1-62. Yes, all those many lines of text are just mod(rand(),62)+1.

Plan A Part 2: Create an array of characters from which to choose
Pickup a string with all the valid characters and also one at the end we don't want (more on that later). The 63 we picked up earlier matches this string length. Take it over to Chop Suey to have it broken into individual passengers.

Plan B: Move the array so we can select a character
One by one, move every character over to Narrow Path Park. It's the only stack available and the only way to not have leftover passengers getting in the way. Everything else in Townsburg is FIFO so I would have to go back and clear out all the passengers every iteration of the overall loop. This way, I can just leave them at the park and they'll get pushed out of the way by the 63 new characters every time. The very first A is likely to never escape.

Plan C: Prepare to select a character
This is really just a few stops that didn't need to be in Plan D. Re-position the taxi in preparation.

Plan D: Get all the characters we dont want
Starting with the first character in the reversed "array" (this is the 63rd character we don't want), keep picking up and concatenating characters as we count down from the result of the mod function in Plan A. Once you hit zero, the next character is the one you want.

Plan E: Drown the ones you don't want and return the chosen one.
"[P]assengers dropped off at Riverview Bridge seem to always fall over the side and into the river..." Well, that gets rid of that concatenated string of losers. Go pick up the next character and send it to stdout. Finally, let's check how many characters we've printed thus far. Back to Sunny Skies to pick up the stdin value we left so long ago. Subtract one and, if the result is more than zero, send it back to wait and start over again at Plan A.

Engineer Toast

Posted 2017-05-05T09:05:16.883

Reputation: 5 769

Is this a Turing complete language? I have never heard of it? If so, then this may qualify as the longest code golf answer in history! – maple_shaft – 2017-05-05T16:38:05.067

4

@maple_shaft Taxi is kind of fun but I can guarantee this is not the longest code golf answer. There are some Unary answers that seriously trump it.

– Engineer Toast – 2017-05-05T18:04:19.867

1

@maple_shaft I did some digging. The largest answer I can find on PPCG is the original version of this answer from @Dennis♦ (of course it's Dennis♦) but that's from code-bowling and was revised down. The longest code-golf answer I could find is the original Brain-Flak submission on the basic quine challenge. It comes it at 9.5*10^580 bytes. The longest current answer I found was a prime tester in Unary: 1.65*10^56 bytes.

– Engineer Toast – 2017-05-08T15:03:09.400

7

C (gcc), 57 55 52 bytes

Thanks to 2501 for the pointers...

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

Try it online!

cleblanc

Posted 2017-05-05T09:05:16.883

Reputation: 3 360

rand()%74 should be rand()%75 – 2501 – 2017-05-05T15:01:16.817

@2501 good call. – cleblanc – 2017-05-05T15:10:19.283

1You can further reduce the size by using &&putchar(i) instead of the ternary operator. – 2501 – 2017-05-05T15:25:56.107

Nice! that's great, thanks. – cleblanc – 2017-05-05T15:30:40.287

6

Jelly, 5 bytes

Missed a trick - see ais523's 4 byter

ØBX$€

Try it online!

How?

ØBX$€ - Main link: n
    € - for each in range(n):
   $  -   last two links as a monad:
ØB    -     "base digits" - yields list of chars "01..9AB...Zab...z"
  X   -     random choice

Jonathan Allan

Posted 2017-05-05T09:05:16.883

Reputation: 67 804

I would not consider a UTF-8 character as having a length of one byte oO ? – m13r – 2017-07-01T15:00:01.910

@m13r Jelly has its own code page - click bytes in the header of my answer to see it. – Jonathan Allan – 2017-07-01T16:17:13.213

5

Shell + pwgen, 13 bytes

pwgen -s $1 1

-s, --secure

Generate completely random, hard-to-memorize passwords.

Sample output

%pwgen -s 10 1
2cyhLovbfT

zeppelin

Posted 2017-05-05T09:05:16.883

Reputation: 7 884

5

Java 8, 183 149 97 88 bytes

n->{for(int t;n-->0;t*=Math.random(),System.out.printf("%c",t+=t>9?t>35?61:55:48))t=62;}

Try it online.

-9 bytes by porting @2501's C answer, so make sure to upvote him as well!

Old answer, 97 bytes

n->{for(int t;n-->0;t*=Math.random(),System.out.printf("%c",t>9?(t<36?65:97)+t%26:48+t%10))t=62;}

Try it online.

Explanation:

n->{                           // Method with integer parameter and String return-type
  for(int t;                   //  Temp integer
      n-->0                    //  Loop the input amount of times:
      ;                        //    After every iteration:
       t*=Math.random(),       //     Set `t` to a random integer in the range [0,62)
       System.out.printf("%c", //     Print as character:
         t+=                   //      The random integer, after we've added:
            t>9?               //       If the random integer is larger than 9:
             t>35?             //        If the random integer is larger than 35:
              61               //         Add 61
             :                 //        Else:
              55               //         Add 55
            :                  //       Else:
             48))              //        Add 48
    t=62;}                     //   (Re)set `t` to 62 for the random

n->{for(int t;n-->0;t*=Math.random(),System.out.printf("%c",...))t=62;}
                               // Similar as above
         t>9?                  //      If the random integer is larger than 9:
          (t<36?               //       If the random integer is smaller than 36:
            65                 //        Start with 65 ('A')
           :                   //       Else:
            97)                //        Start with 97 ('a')
               +t%26           //       And add the random integer modulo-26
         :                     //      Else:
          48                   //       Start with 48 ('0')
            +t%10)             //       And add the random integer modulo-10

Kevin Cruijssen

Posted 2017-05-05T09:05:16.883

Reputation: 67 575

4

PowerShell, 58 54 Bytes

-4 thanks to Andrei Odegov - casting to a char array instead of looping to create a char array.

-join[char[]](65..90+97..122+48..57|random -C "$args")

generates a range 1..2+4..5 = 1,2,4,5 of all the acceptable charachter codes, then selects $args number of elements randomly using random -Count - the resulting elements are looped through |%{} and turned into [char]s, are cast to an array of chars using [char[]] - then the whole thing is encapsulated in brackets and -joined together.

PS C:\users\sweeneyc\Desktop> .\grstr.ps1 5
oaCE5
PS C:\users\sweeneyc\Desktop> .\grstr.ps1 10
UReh6McG7D
PS C:\users\sweeneyc\Desktop> .\grstr.ps1 30
t1YrhZf5egyzqnPlWUKV3cEoIudMTs

Does not work for an input of 0 as Get-Random only accepts numbers above 1 for the -Count parameter.

colsw

Posted 2017-05-05T09:05:16.883

Reputation: 3 195

You can cast the obtained array of bytes as a single whole to an array of chars. This'll help to save 4 bytes: -join[char[]](65..90+97..122+48..57|random -C "$args") – Andrei Odegov – 2017-05-07T05:52:36.910

4

C, 60 bytes

r;f(n){for(;n--;)r=rand()%62,putchar(r+=r>9?r>35?61:55:48);}

See it work here.

See the distribution here.

It is uniformly distributed, assuming rand() % 62 produces a uniform distribution. Since 62 usually doesn't evenly divide RAND_MAX, there is a very small bias.

2501

Posted 2017-05-05T09:05:16.883

Reputation: 748

4

Snowman, 58 bytes

((}#`""*:48vn58nR|65vn91nR,aC|97vn123nR,aCAsH1AaL#aC*;bR))

Try it online!

This is a subroutine that takes an integer as input and returns the random string.

((             subroutine
  }            make b, e, g active
  #`           e = input (from +)
  ""*          store an empty string in +
  :            what follows is the block to prepend a random char to +
    48vn58nR|  generate range(48..58) and place in g (need b and e for next step)
    65vn91nR   generate range(65..91) in b
    ,aC|       move g to e, concatenate b and e, and move the result to g
    97vn123nR  generate range(97..123) in b
    ,aC        move g to e, concatenate b and e, keeping the result in b
    AsH        shuffle the array of candidate ASCII codes stored in b
    1AaL       equivalent to 0aAwR - get the first element wrapped in an array
    #aC        retrieve + and prepend the randomly generated character
    *          store back into +
  ;bR          repeat this block e times, where e has been set to the input
))             output is given via +

Doorknob

Posted 2017-05-05T09:05:16.883

Reputation: 68 138

It should be: ((}#\"":48vn58nR|65vn91nR,aC|97vn123nR,aCAsH1AaL#aC;bR))`. – 2501 – 2017-05-05T12:58:16.617

@2501 Ah, you're right. Fixed, thanks. – Doorknob – 2017-05-05T13:01:18.050

3

PHP, 56 Bytes

for(;$argn;)ctype_alnum($l=chr(rand()))&&$argn-=print$l;

Online Version

ctype_alnum

Jörg Hülsermann

Posted 2017-05-05T09:05:16.883

Reputation: 13 026

2

05AB1E, 6 bytes

FžK.RJ

Try it online!

Explanation

F        # input number of times do
 žK      # push [a-zA-Z0-9]
   .R    # pick one at random
     J   # join to string

Emigna

Posted 2017-05-05T09:05:16.883

Reputation: 50 798

2

Perl 5, 41 bytes

40 bytes of code + -p flag.

$\.=(a..z,A..Z,0..9)[rand 62]for 1..$_}{

Try it online!

(a..z,A..Z,0..9) creates an array containing all letters and numbers, [rand 62] returns an random element of this array, which is append (.=) to $\, which is implicitly printed at the end thanks to -p flag with }{.


Or, for the same bytecount, but using the parameters rather than the standart input:

print+(a..z,A..Z,0..9)[rand 62]for 1..pop

Try it online!

Dada

Posted 2017-05-05T09:05:16.883

Reputation: 8 279

2

JavaScript (ES6), 61 54 39 52 64 bytes

This is almost like reverse-golf! Took a big hit on the byte count ensuring that the full range of characters from all three groups would be used.

f=n=>n--?btoa(String.fromCharCode(Math.random()*248))[0]+f(n):""
  • 15 bytes saved (at one stage) thanks to Arnauld's suggestion of using a recursive function.

Try it

f=n=>n--?btoa(String.fromCharCode(Math.random()*248))[0]+f(n):""
i.addEventListener("input",_=>o.innerText=f(+i.value))
<input id=i type=number><pre id=o>

Shaggy

Posted 2017-05-05T09:05:16.883

Reputation: 24 623

I've updated it so that all 3 character groups are included, @Arnauld; I'm just trying to find an index that can contain more than 2 of them. Thanks for suggesting the recursive option. – Shaggy – 2017-05-05T09:37:18.487

I like the idea, but I think you're now generating characters in [0-5w-z] exclusively. – Arnauld – 2017-05-05T09:42:23.207

I'd suggest btoa(String.fromCharCode(Math.random()*248))[0] to cover the whole range uniformly. – Arnauld – 2017-05-05T09:54:02.760

Just noticed that myself, @Arnauld. It looks like I'm going to have to combine both methods (convert toString and then encode) in order to guarantee a full range of characters from all 3 groups can be returned. – Shaggy – 2017-05-05T09:55:45.060

That's better but still incomplete: 014589ABEFIJMNQRUVYZcdghklopstwx (and not uniform). – Arnauld – 2017-05-05T10:02:27.920

@Arnauld, I've asked if "pseudo-randomness" is OK; will update again when m13r clarifies that. – Shaggy – 2017-05-05T10:09:43.057

The snipped doesn't work for me. Can you post an example on https://tio.run ?

– 2501 – 2017-05-05T12:56:33.393

What browser are you using, @2501? As far as I know, TIO doesn't support vanilla JavaScript and, if it's a browser issue, you'll just run into the same problems there. – Shaggy – 2017-05-05T13:01:19.717

I'm sure it is a problem with my browser. You don't have to bother. – 2501 – 2017-05-05T13:03:59.893

@2501, it won't work in IE, if that's what you're using but it works in Chrome, FF & Edge. – Shaggy – 2017-05-05T13:05:20.030

Yeah, @ETHproductions, I've just updated to Arnauld's solution above. Shame, but them's the rules. – Shaggy – 2017-05-05T15:25:12.967

2

R, 54 52 51 49 bytes

intToUtf8(sample(c(65:90,97:122,48:57),scan(),T))

Explanation:

  1. Read input integer n: scan()
  2. Vector with ASCII values: c(65:90,97:122,48:57)
  3. Sample n ASCII values with replacement: sample(c(65:90,97:122,48:57),scan(),T)
  4. Transform ASCII values to a character string with intToUtf8

Sven Hohenstein

Posted 2017-05-05T09:05:16.883

Reputation: 2 464

I found another approach with the same length. – JAD – 2017-05-05T14:09:45.037

@JarkoDubbeldam Good idea, this helped me to save two bytes – Sven Hohenstein – 2017-05-05T14:13:15.343

D'oh!

nice job :) – JAD – 2017-05-05T14:26:44.870

2

R, 51 bytes

Same length as the other R answer, but a different approach.

cat(sample(c(letters,LETTERS,0:9),scan(),T),sep="")

letters and LETTERS both are built-in variables containing all lower and uppercase letters respectively. Adding 0:9 to that and we have the entire set of alphanumeric characters.

JAD

Posted 2017-05-05T09:05:16.883

Reputation: 2 898

2

Alice, 24 bytes

/w9u"Uz;r
\0.rdao"ki@/t&

Try it online!

This layout is already a lot better than what I originally had (32 bytes), but I'm sure it's not optimal yet...

Explanation

/      Reflect to SE. Switch to Ordinal.
       The IP now bounces diagonally up and down through the code.
09     Append 0 and 9 to an (implicit) empty string to create "09".
r      Range expansion, turns the string into "0123456789".
"az"   Push this string.
r      Range expansion, turns it into the lower-case alphabet.
i      Read all input as a string.
/      Reflect to E. Switch to Cardinal.
t      Implicitly convert the input string to the integer value N it
       contains and decrement it.
&      Run the next command N-1 times.
       The IP wraps around to the first column.
\      Reflect to NE. Switch to Ordinal. (This is not a command.)
w      Push the current IP address to the return address stack N-1
       times. This starts a loop whose body will run N times.
  .      Duplicate the lower-case alphabet.
  u      Convert it to upper case.
  d      Push the concatenation of all values on the stack. This pushes
         a single string with digits, lower-case and upper-case alphabet.
  U      Random choice. Pick a character from this string uniformly at random.
  o      Print it.
  ;      Discard the upper-case alphabet, because it will be regenerated
         in the next loop iteration (and if we leave it, then upper-case
         letters will become more and more likely as the output grows).
k      As long as there is still an address on the return address stack,
       jump back to that address (i.e. to the w). Once the return address
       stack has been depleted, this does nothing and the loop is exited.
@      Terminate the program.

Martin Ender

Posted 2017-05-05T09:05:16.883

Reputation: 184 808

2

Python + exrex, 81 bytes

import exrex,random
lambda n:random.choice(list(exrex.generate("[A-Za-z0-9]"*n)))

a spaghetto

Posted 2017-05-05T09:05:16.883

Reputation: 10 647

2

Python 2, 79 83 79 bytes

import random as r,string as s;lambda x:''.join(r.sample(s.printable[:62]*x,x))

+4 bytes (didn't account for repetition)

-4 bytes (Thanks to @Rod for the suggestion for using printable[:62])

Wondercricket

Posted 2017-05-05T09:05:16.883

Reputation: 251

1Doesn't work, it must contain repetitions. It can be fixed using (s.letters+s.digits)*x instead s.letters+s.digits – Rod – 2017-05-05T18:46:10.170

@Rod Fixed, thanks! – Wondercricket – 2017-05-05T18:50:36.020

You can also use \r.sample(...)`[2::5]instead''.join(r.sample(...))to save a byte (python 2 only) and(s.letters+s.digits)xcan be switched tos.printable[:62]x` to save 4 bytes – Rod – 2017-05-05T19:16:02.137

@Rod Thanks for the suggestions. I implemented printable, couldn't get the [2::5] to work (maybe I was doing it wrong?) – Wondercricket – 2017-05-05T19:23:44.607

you need to surround the list r.sample() with backticks \`` some info about it

– Rod – 2017-05-05T19:27:16.377

@Rod Ah-ha, I got it figured out. But it actually adds a byte after switching to printable (which is py2 and py3 compatible) – Wondercricket – 2017-05-05T19:31:25.037

2

APL (Dyalog Extended), 17 bytes

Full program. Prompts for length.

(?⎕⍴62)⊇⎕A,⎕D,⌊⎕A

Try it online!

⎕A uppercase Alphabet

Lowercased

⎕D, prepended by the Digits

⎕A, prepended by the uppercase Alphabet

()⊇ select the following indices from that:

⍴62 reshape 62 to the following shape:

 prompt for a number

? random indices in in those ranges

Adám

Posted 2017-05-05T09:05:16.883

Reputation: 37 779

1

Pyth, 7 11 bytes

O^s++rG1GUT

Try it online

Explanation

O^s++rG1GUT
    +rG1G      Take the uppercase and lowercase alphabets.
   +     UT    Add it to the list [0, ..., 9].
  s            Concatenate to get a string.
 ^         Q   Get all strings of length N.
O              Choose one at random.

user48543

Posted 2017-05-05T09:05:16.883

Reputation:

This only includes the lowercase alphabet and numbers, not the uppercase letters – Blue – 2017-05-06T11:23:38.827

@muddyfish Good catch. Fixed. – None – 2017-05-06T12:38:31.543

1

MATL, 8 bytes

8Y2iT&Zr

Try it online!

8Y2      % Push string '012...89ABC...YZabc...yz'
i        % Input N
T&Zr     % Sample with replacement. Implicitly display

Luis Mendo

Posted 2017-05-05T09:05:16.883

Reputation: 87 464

1

Brachylog, 14 bytes

~l{Ạụ:Ạ:Ịcṛ}ᵐc

Try it online!

Explanation

~l                 Create a list of length Input
  {        }ᵐ      Map on each element of that list:
   Ạụ:Ạ:Ịc           The string "A…Za…z0…9"
          ṛ          Pick a character at random
             c     Concatenate into a single string

Fatalize

Posted 2017-05-05T09:05:16.883

Reputation: 32 976

1

Batch, 175 bytes

@set s=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
@for /l %%i in (1,1,%1)do @call :c
@echo %s:~62%
:c
@set/an=%random%%%62
@call set s=%s%%%s:~%n%,1%%

s performs double duty here as it contains both the alphanumeric list and the randomly selected characters. After printing the result the code falls through to the subroutine whose result is ignored.

Neil

Posted 2017-05-05T09:05:16.883

Reputation: 95 035

1

Pyke, 4 bytes

~JfH

Try it online!

~J   -   "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  f  -  cominbations(^, length=input)
   H - random.choice(^)

Blue

Posted 2017-05-05T09:05:16.883

Reputation: 26 661

This doesn't seem to work for any input greater than 3, and I'm not sure it can generate the same character more than once. – ATaco – 2017-05-08T07:15:14.483

This does not work for inputs greater than 3. I've tried it here: http://pyke.catbus.co.uk/

– m13r – 2017-06-28T10:31:45.413

This needs about 1 GB of RAM just to create a string of 4 alphanumeric characters... Did not get it to work for an input of 10. The program crashed with a MemoryError – m13r – 2017-07-01T15:05:07.233

1

C# - 121 bytes

void g(int n){Console.Write(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(new Random().Next().ToString())).Substring(0,n));}

John Hathwood

Posted 2017-05-05T09:05:16.883

Reputation: 283

1

Bash, 43 bytes

shuf -ern$1 {a..z} {A..Z} {0..9}|tr -d "\n"

Try it online!

marcosm

Posted 2017-05-05T09:05:16.883

Reputation: 986

1

Pip, 13 bytes

LaORCz.AZ.J,t

Try it online!

Explanation

               a is cmdline arg; t is 10; z is lcase alphabet; AZ is ucase (implicit)
La             Do the following, a times:
  O             Output (without newline)
   RC           random choice from:
     z           Lowercase letters
      .AZ        concatenated with uppercase letters
         .J,t    concatenated with range(10) joined into a string

DLosc

Posted 2017-05-05T09:05:16.883

Reputation: 21 213

1

Sinclair ZX81/Timex TS1000/1500 BASIC, ~63 tokenized BASIC bytes

 1 INPUT N
 2 IF NOT N THEN STOP
 3 FOR N=SGN PI TO N
 4 PRINT CHR$ (CODE "A"+RND*26);
 5 NEXT N

There are no lower-case characters in ZX81 without using assembly or having some sort of UDG ROM or something, and for the time being, it only outputs A-Z. If zero is entered then the program halts and returns to direct mode.

Shaun Bebbers

Posted 2017-05-05T09:05:16.883

Reputation: 1 814

1

Japt, 12 8 bytes

;BiCí)öU

Try it

Shaggy

Posted 2017-05-05T09:05:16.883

Reputation: 24 623

0

Stacked, 33 bytes

:>[alpha 10:>ALPHA,,''#`randin]"!

Try it online! Takes input from the top of the stack and leaves output on the top of the stack.

:>[alpha 10:>ALPHA,,''#`randin]"!
:>                                  range from 0 to n-1
  [                           ]"!   on each, do:
   alpha                            push "abc...xyz"
         10:>                       push (0 1 2 ... 8 9)
             ALPHA                  push "ABC...XYZ"
                  ,,                concat twice
                    ''#`            join by nothing
                        randin      select random member in it

Conor O'Brien

Posted 2017-05-05T09:05:16.883

Reputation: 36 228

0

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.

LiefdeWen

Posted 2017-05-05T09:05:16.883

Reputation: 3 381

1Hi, 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 – 2017-05-05T13:58:54.293

0

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!

totallyhuman

Posted 2017-05-05T09:05:16.883

Reputation: 15 378

1Here is an improved version based on an older revision (114 bytes) – ovs – 2017-05-05T15:14:57.797

I had to downvote for a meme but you said it was fine :P – Christopher – 2017-05-08T00:27:34.300

0

Mathematica 66 Bytes

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

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

Kelly Lowder

Posted 2017-05-05T09:05:16.883

Reputation: 3 225

0

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.

Blab

Posted 2017-05-05T09:05:16.883

Reputation: 451

You can save five bytes by replacing string.char with s.char. – Josh – 2017-05-06T18:41:34.777

@Josh while it is frustrating for people to not respond to your suggestions, edits are not for improving someone else's code.

– Cyoce – 2017-05-06T19:36:02.157

@Josh Change made. Didn't actually know I could do that. Good to know for the future. Thanks. – Blab – 2017-05-07T04:54:03.347

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 – 2017-05-07T12:03:51.390

0

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?

Johan du Toit

Posted 2017-05-05T09:05:16.883

Reputation: 1 524

1How 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̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2017-05-06T15:10:07.500

It doesn't. This is what happens when you mix coding and alcohol ;) – Johan du Toit – 2017-05-06T15:23:13.883

This can random seg fault because it read memory possible do not own from the program – RosLuP – 2017-05-08T08:17:17.177

0

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

Esolanging Fruit

Posted 2017-05-05T09:05:16.883

Reputation: 13 542

0

C, 54 52 bytes

  • -2 bytes, thanks to @RosLuP

Try Online

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

Khaled.K

Posted 2017-05-05T09:05:16.883

Reputation: 1 435

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... – RosLuP – 2017-05-08T07:26:36.490

0

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.

NikoNyrh

Posted 2017-05-05T09:05:16.883

Reputation: 2 361

0

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]

RosLuP

Posted 2017-05-05T09:05:16.883

Reputation: 3 036

0

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

RosLuP

Posted 2017-05-05T09:05:16.883

Reputation: 3 036

0

Ruby, 47 bytes

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

Try it online!

daniero

Posted 2017-05-05T09:05:16.883

Reputation: 17 193

0

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.

ბიმო

Posted 2017-05-05T09:05:16.883

Reputation: 15 345

no longer valid – ASCII-only – 2019-01-30T06:08:55.523

@ASCII-only: Updated. – ბიმო – 2019-01-31T14:55:36.530

0

PHP, 51 bytes

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

Run as pipe with -nR or try it online.

Titus

Posted 2017-05-05T09:05:16.883

Reputation: 13 814