How to generate a random number in C++?

Using modulo may introduce bias into the random numbers, depending on the random number generator. See this question for more info. Of course, it’s perfectly possible to get repeating numbers in a random sequence. Try some C++11 features for better distribution: #include <random> #include <iostream> int main() { std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // … Read more

Random row selection in Pandas dataframe

With pandas version 0.16.1 and up, there is now a DataFrame.sample method built-in: import pandas df = pandas.DataFrame(pandas.np.random.random(100)) # Randomly sample 70% of your dataframe df_percent = df.sample(frac=0.7) # Randomly sample 7 elements from your dataframe df_elements = df.sample(n=7) For either approach above, you can get the rest of the rows by doing: df_rest = … Read more

How can I get a random number in Kotlin?

My suggestion would be an extension function on IntRange to create randoms like this: (0..10).random() TL;DR Kotlin >= 1.3, one Random for all platforms As of 1.3, Kotlin comes with its own multi-platform Random generator. It is described in this KEEP. The extension described below is now part of the Kotlin standard library, simply use … Read more

Random shuffling of an array

Using Collections to shuffle an array of primitive types is a bit of an overkill… It is simple enough to implement the function yourself, using for example the Fisher–Yates shuffle: import java.util.*; import java.util.concurrent.ThreadLocalRandom; class Test { public static void main(String args[]) { int[] solutionArray = { 1, 2, 3, 4, 5, 6, 16, 15, … Read more

Random alpha-numeric string in JavaScript?

I just came across this as a really nice and elegant solution: Math.random().toString(36).slice(2) Notes on this implementation: This will produce a string anywhere between zero and 12 characters long, usually 11 characters, due to the fact that floating point stringification removes trailing zeros. It won’t generate capital letters, only lower-case and numbers. Because the randomness … Read more

How to randomly select rows in SQL?

SELECT TOP 5 Id, Name FROM customerNames ORDER BY NEWID() That said, everybody seems to come to this page for the more general answer to your question: Selecting a random row in SQL Select a random row with MySQL: SELECT column FROM table ORDER BY RAND() LIMIT 1 Select a random row with PostgreSQL: SELECT … Read more