How do you generate uniformly distributed random integers?

The simplest (and hence best) C++ (using the 2011 standard) answer is: #include <random> std::random_device rd; // Only used once to initialise (seed) engine std::mt19937 rng(rd()); // Random-number engine used (Mersenne-Twister in this case) std::uniform_int_distribution<int> uni(min,max); // Guaranteed unbiased auto random_integer = uni(rng); There isn’t any need to reinvent the wheel, worry about bias, or … Read more

Generating multiple random (x, y) coordinates, excluding duplicates?

This is a variant on Hank Ditton’s suggestion that should be more efficient time- and memory-wise, especially if you’re selecting relatively few points out of all possible points. The idea is that, whenever a new point is generated, everything within 200 units of it is added to a set of points to exclude, against which … Read more

Obscure / encrypt an order number as another number: symmetrical, “random” appearance?

Pick a 8 or 9 digit number at random, say 839712541. Then, take your order number’s binary representation (for this example, I’m not using 2’s complement), pad it out to the same number of bits (30), reverse it, and xor the flipped order number and the magic number. For example: 1 = 000000000000000000000000000001 Flip = … Read more

Best way to seed mt19937_64 for Monte Carlo simulations

Use std::random_device to generate the seed. It’ll provide non-deterministic random numbers, provided your implementation supports it. Otherwise it’s allowed to use some other random number engine. std::mt19937_64 prng; seed = std::random_device{}(); prng.seed(seed); operator() of std::random_device returns an unsigned int, so if your platform has 32-bit ints, and you want a 64-bit seed, you’ll need to … Read more

How to generate a random, unique, alphanumeric ID of length N in Postgres 9.6+?

Figured this out, here’s a function that does it: CREATE OR REPLACE FUNCTION generate_uid(size INT) RETURNS TEXT AS $$ DECLARE characters TEXT := ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789’; bytes BYTEA := gen_random_bytes(size); l INT := length(characters); i INT := 0; output TEXT := ”; BEGIN WHILE i < size LOOP output := output || substr(characters, get_byte(bytes, i) % l … Read more

undefined reference to `log’

I don’t know what the reason is, but if you move -lm to the end, it will compile. $ cc -o randomselection rfc3797.c MD5.c -lm rfc3797.c: In function ‘getinteger’: rfc3797.c:183:3: warning: format not a string literal and no format arguments [-Wformat-security]

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)