Generating random numbers in Objective-C

You should use the arc4random_uniform() function. It uses a superior algorithm to rand. You don’t even need to set a seed. #include <stdlib.h> // … // … int r = arc4random_uniform(74); The arc4random man page: NAME arc4random, arc4random_stir, arc4random_addrandom — arc4 random number generator LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <stdlib.h> u_int32_t arc4random(void); … Read more

How to generate a random string in Ruby

(0…8).map { (65 + rand(26)).chr }.join I spend too much time golfing. (0…50).map { (‘a’..’z’).to_a[rand(26)] }.join And a last one that’s even more confusing, but more flexible and wastes fewer cycles: o = [(‘a’..’z’), (‘A’..’Z’)].map(&:to_a).flatten string = (0…50).map { o[rand(o.length)] }.join If you want to generate some random text then use the following: 50.times.map { … Read more

Understanding “randomness”

Just a clarification Although the previous answers are right whenever you try to spot the randomness of a pseudo-random variable or its multiplication, you should be aware that while Random() is usually uniformly distributed, Random() * Random() is not. Example This is a uniform random distribution sample simulated through a pseudo-random variable: BarChart[BinCounts[RandomReal[{0, 1}, 50000], … Read more

Shuffling a list of objects

random.shuffle should work. Here’s an example, where the objects are lists: from random import shuffle x = [[i] for i in range(10)] shuffle(x) print(x) # print(x) gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]] Note that shuffle works in place, and returns None. More generally in Python, mutable objects can be passed … Read more

PHP random string generator

To answer this question specifically, two problems: $randstring is not in scope when you echo it. The characters are not getting concatenated together in the loop. Here’s a code snippet with the corrections: function generateRandomString($length = 10) { $characters=”0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”; $charactersLength = strlen($characters); $randomString = ”; for ($i = 0; $i < $length; $i++) { $randomString … Read more

How can I generate random alphanumeric strings?

I heard LINQ is the new black, so here’s my attempt using LINQ: private static Random random = new Random(); public static string RandomString(int length) { const string chars = “ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”; return new string(Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]).ToArray()); } (Note: The use of the Random class makes this unsuitable for anything security related, such as … Read more