Random string generation with upper case letters and digits

Answer in one line: ”.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) or even shorter starting with Python 3.6 using random.choices(): ”.join(random.choices(string.ascii_uppercase + string.digits, k=N)) A cryptographically more secure version: see this post ”.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N)) In details, with a clean function for further reuse: >>> import string >>> import random >>> … Read more

How to randomize (shuffle) a JavaScript array?

The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle. You can see a great visualization here (and the original post linked to this) function shuffle(array) { let currentIndex = array.length, randomIndex; // While there remain elements to shuffle. while (currentIndex != 0) { // Pick a remaining element. randomIndex = Math.floor(Math.random() * currentIndex); … Read more

How to generate a random alpha-numeric string

Algorithm To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length. Implementation Here’s some fairly simple and very flexible code for generating random identifiers. Read the information that follows for important application notes. public class RandomString { /** * Generate a random string. … Read more

How can I randomly select an item from a list?

Use random.choice(): import random foo = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] print(random.choice(foo)) For cryptographically secure random choices (e.g., for generating a passphrase from a wordlist), use secrets.choice(): import secrets foo = [‘battery’, ‘correct’, ‘horse’, ‘staple’] print(secrets.choice(foo)) secrets is new in Python 3.6. On older versions of Python you can use the random.SystemRandom class: import random … Read more

How do I generate a random integer in C#?

The Random class is used to create random numbers. (Pseudo-random that is of course.). Example: Random rnd = new Random(); int month = rnd.Next(1, 13); // creates a number between 1 and 12 int dice = rnd.Next(1, 7); // creates a number between 1 and 6 int card = rnd.Next(52); // creates a number between … Read more

Generating random whole numbers in JavaScript in a specific range

There are some examples on the Mozilla Developer Network page: /** * Returns a random number between min (inclusive) and max (exclusive) */ function getRandomArbitrary(min, max) { return Math.random() * (max – min) + min; } /** * Returns a random integer between min (inclusive) and max (inclusive). * The value is no lower than … Read more