Gerando uma sequência alfanumérica aleatória de comprimento N

30

Qual é a maneira mais curta de gerar uma sequência aleatória com um determinado comprimento e apenas caracteres alfanuméricos permitidos?

  • exemplo de uma sequência aleatória: com N = 9 a saída seria aZua7I0Lk
  • pode-se supor que o comprimento especificado N seja sempre maior que 0
  • se necessário, você pode assumir 256 como um valor máximo para N, mas são preferidas soluções com limites mais altos para N e ainda com um tempo de computação rápido
  • caracteres permitidos: 0-9, az e AZ
  • um caractere pode ocorrer mais de uma vez na sequência de saída
  • cada sequência possível deve ser igualmente provável (com a precisão do gerador de números aleatórios do seu idioma)
m13r
fonte
1
Podemos assumir um valor máximo para N?
JAD
Relacionado.
um spaghetto

Respostas:

4

Gelatina , 4 bytes

ØBṗX

Experimente online!

Explicação

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

O poder cartesiano basicamente gera toda a lista de um determinado comprimento que pode ser formado a partir de um determinado conjunto de elementos; é exatamente disso que precisamos aqui.


fonte
Se houver caracteres UTF-8 envolvidos, seria realmente apenas 4 bytes? Um UTF-8 personagem poderia ser mais do que apenas um byte ...
M13R
@ M13R Jelly utiliza a sua própria página de código em que estes são todos os únicos caracteres de byte
FlipTack
13

Táxi , 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]

Experimente online!

O táxi não é super feito para isso, mas você pode fazê-lo! Vou tentar explicar o que está acontecendo abaixo da versão sem golfe.

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]

Iniciar: Obter stdin
Escolha o valor stdin como texto, converta-o em um número e cole-o em algum lugar para aguardar.

Planeje A Parte 1: Obtenha um número inteiro aleatório 1-62
Obtenha um número inteiro aleatório e depois obtenha 62um número. Duplique o número inteiro aleatório e o 62porque precisaremos deles mais tarde. Você pode transportar apenas 3 passageiros de uma só vez, então acabamos com rand,rand e 62. (O outro 62vai esperar até voltarmos.) Go divisão randpor 62e truncar o resultado para obter um inteiro. Volte para obter a outra cópia 62e multiplique-a pelo número inteiro truncado da divisão. Por fim, subtraia o produto da primeira cópia de rand. Isso nos dá um número de 0 a 61. Agora temos que voltar ao captador a 1e adicioná-lo ao resultado para obter o número 1-62. Sim, todas essas muitas linhas de texto são justas mod(rand(),62)+1.

Planeje uma parte 2: crie uma matriz de caracteres para escolher
Coletar uma sequência com todos os caracteres válidos e também uma no final que não queremos (mais sobre isso mais tarde). O 63que escolhemos anteriormente corresponde a esse comprimento de string. Leve-o até Chop Suey para quebrá-lo em passageiros individuais.

Plano B: Mova a matriz para que possamos selecionar um caractere.
Um por um, mova todos os caracteres para o Narrow Path Park. É a única pilha disponível e a única maneira de não ter sobras de passageiros no caminho. Tudo o resto em Townsburg é FIFO, então eu teria que voltar e limpar todos os passageiros a cada iteração do circuito geral. Dessa forma, eu posso simplesmente deixá-los no parque e eles serão empurrados para fora do caminho pelos 63 novos personagens todas as vezes. AÉ provável que o primeiro nunca escape .

Plano C: Prepare-se para selecionar um personagem. Na
verdade, são apenas algumas paradas que não precisavam estar no Plano D. Reposicione o táxi em preparação.

Plano D: Consiga todos os personagens que não queremos.
Começando com o primeiro caractere no "array" invertido (este é o 63º caractere que não queremos), continue escolhendo e concatenando caracteres à medida que fazemos a contagem regressiva do resultado da modfunção no plano A. Depois de atingir zero, o próximo personagem é o que você deseja.

Plano E: Afogue os que você não quer e devolva o escolhido.
"Os assaltantes [P] deixados na ponte Riverview parecem sempre cair do lado e entrar no rio ..." Bem, isso se livra dessa cadeia concatenada de perdedores. Vá pegar o próximo personagem e envie para stdout. Por fim, vamos verificar quantos caracteres foram impressos até o momento. De volta ao Sunny Skies para pegar o valor stdin que deixamos há tanto tempo. Subtraia um e, se o resultado for maior que zero, envie-o novamente para aguardar e reinicie no Plano A.

Engenheiro Toast
fonte
Esse é um idioma completo de Turing? Eu nunca ouvi falar disso? Nesse caso, isso pode ser considerado a resposta de golfe com código mais longa da história!
Maple_shaft
4
@maple_shaft O táxi é divertido, mas posso garantir que essa não é a resposta mais longa para o código de golfe. Existem algumas respostas Unárias que superam isso seriamente.
Engineer Toast
1
@maple_shaft Fiz algumas escavações. A maior resposta que posso encontrar no PPCG é a versão original desta resposta de @ Dennis ♦ (é claro que é Dennis ♦), mas é de code-bowlinge foi revisada. A code-golfresposta mais longa que pude encontrar é a submissão original do Brain-Flak sobre o desafio básico do quine. Ele vem em 9,5 * 10 ^ 580 bytes. A resposta atual mais longa que encontrei foi um testador principal no Unary : 1,65 * 10 ^ 56 bytes.
Engineer Toast
7

C (gcc) , 57 55 52 bytes

Graças a 2501 pelos ponteiros ...

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

Experimente online!

cleblanc
fonte
rand()%74deveria serrand()%75
2501 05/05
@ 2501 boa ligação.
Cleblanc 5/05
1
Você pode reduzir ainda mais o tamanho usando em &&putchar(i)vez do operador ternário.
2501
Agradável! isso é ótimo, obrigado.
Cleblanc 5/05
6

Gelatina , 5 bytes

Faltou um truque - veja 4 byter de ais523

ØBX$€

Experimente online!

Quão?

Ø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
fonte
Eu não consideraria um caractere UTF-8 como tendo um byte oO?
M13r 01/07/19
@ m13r Jelly tem sua própria página de código - clique em bytes no cabeçalho da minha resposta para vê-la.
Jonathan Allan
5

Shell + pwgen , 13 bytes

pwgen -s $1 1

-s, --secure

Gere senhas completamente aleatórias e difíceis de memorizar.

Saída de amostra

%pwgen -s 10 1
2cyhLovbfT
zepelim
fonte
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;}

Experimente online.

-9 bytes, portando a resposta C de @ 2501 , certifique-se de votar também nele!

Resposta antiga, 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;}

Experimente online.

Explicação:

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
fonte
4

C, 60 bytes

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

Veja como funciona aqui .

Veja a distribuição aqui .

É uniformemente distribuído, assumindo que rand() % 62produz uma distribuição uniforme. Como 62 geralmente não divide uniformemente RAND_MAX, há um viés muito pequeno.

2501
fonte
4

Boneco de neve , 58 bytes

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

Experimente online!

Esta é uma sub-rotina que recebe um número inteiro como entrada e retorna a sequência aleatória.

((             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 +
Maçaneta da porta
fonte
Ele deve ser: ((}#`""*:48vn58nR|65vn91nR,aC|97vn123nR,aCAsH1AaL#aC*;bR)).
2501 05/05
@ 2501 Ah, você está certo. Corrigido, obrigado.
Maçaneta
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
fonte
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
3

PHP, 56 Bytes

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

Online Version

ctype_alnum

Jörg Hülsermann
fonte
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
fonte
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
fonte
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
fonte
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
fonte
I found another approach with the same length.
JAD
@JarkoDubbeldam Good idea, this helped me to save two bytes
Sven Hohenstein
D'oh! nice job :)
JAD
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
fonte
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
I like the idea, but I think you're now generating characters in [0-5w-z] exclusively.
Arnauld
I'd suggest btoa(String.fromCharCode(Math.random()*248))[0] to cover the whole range uniformly.
Arnauld
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
That's better but still incomplete: 014589ABEFIJMNQRUVYZcdghklopstwx (and not uniform).
Arnauld
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
fonte
2

Python + exrex, 81 bytes

import exrex,random
lambda n:random.choice(list(exrex.generate("[A-Za-z0-9]"*n)))
a spaghetto
fonte
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
fonte
1
Doesn't work, it must contain repetitions. It can be fixed using (s.letters+s.digits)*x instead s.letters+s.digits
Rod
@Rod Fixed, thanks!
Wondercricket
You can also use `r.sample(...)`[2::5] instead ''.join(r.sample(...)) to save a byte (python 2 only) and (s.letters+s.digits)*x can be switched to s.printable[:62]*x to save 4 bytes
Rod
@Rod Thanks for the suggestions. I implemented printable, couldn't get the [2::5] to work (maybe I was doing it wrong?)
Wondercricket
you need to surround the list r.sample() with backticks `` some info about it
Rod
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
fonte
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
fonte
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
fonte
1

Pyke, 4 bytes

~JfH

Try it online!

~J   -   "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  f  -  cominbations(^, length=input)
   H - random.choice(^)
Blue
fonte
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
This does not work for inputs greater than 3. I've tried it here: pyke.catbus.co.uk
m13r
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
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.

fonte
This only includes the lowercase alphabet and numbers, not the uppercase letters
Blue
@muddyfish Good catch. Fixed.
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
fonte
1

APL (Dyalog) with AGL, 17 bytes

(⎕A,∆a,⎕D)[?⎕⍴62]

Try it online!

()[] index into

⎕A,∆a,⎕D uppercase alphabet followed by lowercase alphabet followed by digits

using

62 (the number of possible symbols

reshaped by

 evaluated input (n)

? change each 62 into a random number in the range 1…62

APL (APLX), 17 bytes

(⎕A,⎕a,⎕D)[?⎕⍴62]
Adám
fonte
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
fonte
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
fonte
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
fonte