Random Number Generation In Various Programming Languages

Ankur Ingale
6 min readAug 7, 2018

--

Hey! I am back with another one.

This blog is a compilation for generating random numbers in my favourite programming languages. My purpose is to have a single source to learn random number generation in the programming language you are currently working on.

Random number generation is one of the most important aspects of programming. Many card games are played on luck. This luck is nothing but getting a random card. Also, random number generation has applications in statistical sampling, cryptography, gambling and much more. This is the THING which runs the entire Las Vegas!!

In programming, random number generation is mainly used in basic examples like rolling of dice, flipping of a coin or shuffling a deck of playing cards. In my previous blog I used random numbers to get 3 different colours (link here).

Haaa! That’s too much of intro. Let’s begin at once….

JavaScript

JavaScript is one of the popular programming languages. JavaScript is a universal programming language which shows a great level of flexibility and performance. It is free to use, easy to learn, and easy to implement (both in web and hybrid mobile applications). All these reasons combined make it the perfect cross-platform programming language.

So how to generate random numbers in this language? The following code does it:

var rand = Math.random();

Here, the variable rand stores a random value between 0(inclusive) and 1(exclusive). To generate a random number between 1 to N, the following code is used:

var rand = Math.floor(Math.random * N) + 1;

First, we get a random fraction between 0 and 1. Then, we multiply this random fraction with the upper limit (in this case, it is N). Generated number is a product ranging between 0 and N (0 x N = 0, 1 x N = N).

Lastly, we floor it i.e. we take the closest whole number which is less than or equal to that product. This floored product is between 0 and N-1. This is because 1 is exclusive. Hence there is no way for N to be selected as a random value in our above product. Finally, the floored product is incremented by 1. The overall equation now comes in the range of 1 to N (both inclusive).

Java

Java is one of the “slowly dying” programming languages. But even today, it has many applications as compared to others. The key features of Java are speed, safety, and cross-platform applications. The main areas of Java include Android App development, Software development and much more.

Let’s see how to generate random numbers:

double rand = Math.random();

Same as JavaScript? The answer is ‘YES’. But is this the only way? Not at all!

The Random class in java.util package gives us everything we need. This class was implemented in my previous blog. So if you want to see a working example, read my previous blog here.

Note: Make sure you import this class before working on ahead.

Therefore, to get a random number between 1 to N, we use the following code:

Random rand = new Random();int r1 = rand.nextInt(N) + 1;

C++

Here’s the trouble! But first, let me introduce this guy.

C++ is a widely used programming language. It is basically an extension of C and includes features like object-oriented programming. It is much more difficult to learn but consequently gives the programmer more control over his code. Main applications of C++ include competitive programming, video games, and financial applications. In fact, it can be used for almost all purposes.

How to generate random numbers with C++? The following code will generate a random number between 1 to N:

int r = rand() % N + 1;

The function rand() returns an integer between 0 and RAND_MAX . By taking the remainder i.e modulus, we are limiting the maximum value the function can return to N-1. Finally, adding 1 to it will give us a random value between 1 to N (both inclusive).

Did you notice something in your code’s output? Is the random value or the sequence of random values generated always same? I ran the following code many times but got the same result:

for (int i = 0; i < 5; i++)
cout << rand() % 5 << endl;

This is because we never talked about pseudo-random numbers and truly random numbers. The reason is that a random number generated from the rand() function isn’t actually random. It is simply a transformation (click here to know more on pseudo-random number generation). Every time you call rand() it takes the seed or the last random number(s) generated, runs a mathematical operation on those numbers and returns the result. So if the seed state is the same each time (as it is if you don’t call srand with a truly random number), then you will always get the same ‘random’ numbers out. The following code solves it:

#include <iostream>
#include <time.h>
using namespace std;int main() {
srand(time(NULL));
for (int i = 0; i < 5; i++) {
cout << rand() % 5 << endl;
}
return 0;
}

Now it’s truly random!

Python

The language of the future is here! Python is a high-level programming language which can be used as a scripting language or for object-oriented programming. Python can do anything. There are so many libraries, both built-in and third-party, which help Python do anything from as simple as writing “Hello World!” in one line to become one of the best language for implementing machine learning algorithms.

But we are here just for generating random numbers. This can be done as follows:

import random
print random.randint(0, 5)

This will output either 1, 2, 3, 4 or 5. If you want a larger number, you can multiply it. For example, a random number between 0 and 100 can be produced as follows:

random.random() * 100

Python also has built-in functions for getting a random choice from a list, shuffling a list, and much more.

import randommyList = [2, 109, False, 10, “Lorem”, 482, “Ipsum”]random.choice(myList)
#random element from list
random.shuffle(list)
#shuffled the list
#example = [109, 2, 10, “Loren”, False, “Ipsum”, 482]

You can learn more about generating random numbers using python here.

Swift

The programming language Swift was developed by Apple to incorporate and improve many features of the programming language Objective-C. Swift is a modern language and an easy tool to use. It is the foundation of iOS development.

The following code generates random number between 0 and 10 (both inclusive):

let number = Int.random(in: 0 … 10)

This code will generate random numbers between 0(inclusive) and 10(exclusive):

let number = Int.random(in: 0 ..< 10)

We also have boolean random generator in Swift. This can be implemented in the following way:

let b = Bool.random()

Lastly, we can also generate random fractions like this:

let number = Float.random(in: 0 ..< 1)

Swift, like Python, also has built-in functions for returning a random element from an array or to shuffle an array:

let names = [“Ford”, “Zaphod”, “Trillian”, “Arthur”, “Marvin”]let randomName = names.randomElement()
//got a random element from `names`
names.shuffle()
//`names` can now be: [“Zaphod”, “Marvin”, “Arthur”, “Ford”, “Trillian”]

You can learn more about generating random numbers using swift here.

C#

C# is very similar to Java but is much more difficult. It is one of the most advanced and convenient programming languages around. It is used to create Windows applications, XML Web services, client-server applications and database applications.

The random number generation is just like the Random class in Java. See the code below:

Random rnd = new Random();int month = rnd.Next(1, 13); // creates a number between 1 and 12int dice = rnd.Next(1, 7); // creates a number between 1 and 6int card = rnd.Next(52); // creates a number between 0 and 51

That was a lot of coding. But with this blog, we were able to learn the different methods of generating random numbers in various programming languages. With this knowledge, you might even start-up your own casino in Las Vegas! Make sure you hit that clap button 50 times if you loved this blog.

Till then, see ya!

--

--