Logo

Programming-Idioms

  • Java
  • Ruby
  • Haskell
  • Python

Idiom #317 Random string

Create a string s of n characters having uniform random values out of the 62 alphanumeric values A-Z, a-z, 0-9

from random import shuffle
from string import ascii_letters, digits
a = list(ascii_letters + digits)
shuffle(a)
s = ''.join(a[:n])
import random
import string
alphanum = string.ascii_letters + string.digits
s = ''.join(random.choices(alphanum, k=n))
import static java.util.Arrays.asList;
import static java.util.Collections.shuffle;
String s = "";
Integer z[], i = 0;
char a[] = new char[62], c;
for (c = 'a'; c <= 'z'; ++c) a[i++] = c;
for (c = 'A'; c <= 'Z'; ++c) a[i++] = c;
for (c = '0'; c <= '9'; ++c) a[i++] = c;
z = new Integer[62];
for (i = 0; i < 62; ++i) z[i] = i;
shuffle(asList(z));
for (i = 0; i < n; ++i) s = s + a[z[i]];
require 'securerandom'
s = SecureRandom.alphanumeric(n)
import "math/rand"
const alphanum = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

func randomString(n int) string {
	a := make([]byte, n)
	for i := range a {
		a[i] = alphanum[rand.Intn(len(alphanum))]
	}
	return string(a)
}

Each of these runes fits in a single byte.
The default RNG can be run concurrently, as it incurs the cost of a Mutex.
Note that the package math/rand is not crypto-secure

New implementation...