Generating Random Data in C++, Node.js, Python and Go [Coding Series #1]

When testing a piece of code whether it's during a hackathon, software competition, at work or for a side project, you might want to generate random data to see how your program behaves. Sometimes it's for proofing your code, sometimes it's for testing it out with more than just dumb fixtures. When you start having some experience in coding, the thing is you are going to manipulate different types of coding languages and it's quite good to become polyglot. Not only because you learn a new syntax but also because other languages have paradigms you've never heard of so far and it trains the mind to think differently.

Here I'm trying to make this exercice to create random data in the languages I use the most on a day to day basis : C++, Python, JS (Node.js), and Go.

Generating a random number

One of the use cases we are going to work on is generating a random number.

C++ (easy way)

I'm working with the C standard library over here as it's the simplest way to compute pseudo random number in C++.

#include <cstdlib>
#include <iostream>
#include <ctime>

using namespace std;

int main(){
    srand(time(NULL)); // using time to generate the seed
    int a = rand(); // calling the random function
    cout << a << endl;
    return 0;
}

C++11 (the right way)

This way is the more modern one which will let you use a varied range of generators and will produce result a varied range of distributions. Here's an example with the Mersenne Twister used by CPython.
For more information on the reason for this change, check that out: https://stackoverflow.com/questions/16536617/random-engine-differences.

#include <iostream>
#include <chrono>
#include <random>

using namespace std;

int main (){
    unsigned seed1 = chrono::system_clock::now().time_since_epoch().count();
    mt19937 g1 (seed1);  // mt19937 is a standard mersenne_twister_engine
    cout << "A time seed produced: " << g1() << endl;
    return 0;
}

Python 3

import random
from sys import maxsize

random.seed(datetime.now())
print(random.randrange(maxsize))

JS (Node.js)

Here the seed cannot be chosen.

var a = Math.ceil( Math.random() * Number.MAX_SAFE_INTEGER );
console.log(a);

Go

package main

import "math/rand"
import "fmt"
import "time"

func main() {
    rand.Seed(time.Now().UTC().UnixNano())
    a := rand.Int()
    fmt.Println(a)
}

Generate a random string

In some cases, it's good to be able to generate a random string.

The algorithm we are going to use is simple.

s <- init empty string
A <- Array Of All Char Allowed
a_len <- len(A)
s_len <- init wanted string length

while(s not the size of s_len)
    i <- rand(0, a_len-1)
    s = s + A[i]

return s

C++

Now let's try to code this algorithm in C++.

#include <iostream> 
#include <string>
#include <random>

using namespace std;

int main(){
    unsigned seed1 = chrono::system_clock::now().time_since_epoch().count();
    mt19937 g1 (seed1);
    const char a[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    auto idx_rand = bind(uniform_int_distribution<int>(0,sizeof(a)-1), g1);
    int s_len = 10;  
    string s;
    s.reserve(s_len+1);
    
    for (int i = 0; i < s_len; ++i) {
        s +=  a[idx_rand()];
    }
    s[s_len] = 0;
    cout << s << endl;
}

Python

import random
from datetime import datetime

s_len = 10
s = ''
random.seed(datetime.now())
a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
a_len = len(a)
for i in range(s_len):
    s += random.choice(a)
print(s)

JS (Node.js)

var a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var s = '';
var s_len = 10;
for(var i = 0; i < s_len; i++){
    s += a[Math.ceil( Math.random() * (a.length-1) )];
}
console.log(s); 

Go

For Go, I found a nice stackoverflow question that optimizes the generation, worth a read to look for optimizations: https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang
I chose to optimize part of it for the sake of the code being decently readable.

package main

import "math/rand"
import "fmt"
import "time"

func main() {
	rand.Seed(time.Now().UTC().UnixNano())
	s_len := 10
	const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

	b := make([]byte, s_len)
	for i := range b {
		b[i] = letters[rand.Int63()%int64(len(letters))]
	}
	fmt.Println(string(b))
}

Generate a matrix of random numbers

This part will show as well how to create a matrix (2D) and initialize with random numbers. When you are dealing with loads or data and / or Neural networks, this can be quite useful.
We are building a 2D Matrix of size N x M.

C++

#include <iostream> 
#include <string>
#include <random>

using namespace std;

int main(){
    unsigned seed1 = chrono::system_clock::now().time_since_epoch().count();
    mt19937 g1 (seed1);
    
    int n = 10; 
    int m = 9;
    int matrix[n][m]; 
    for (int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++){
            matrix[i][j] = g1();
        }
    }
    // display
    cout << "[" << endl;
    for(int i = 0; i < n-1; i++){
        cout << "\t" << "[";
        for(int j = 0; j < m-1; j++){
            cout << matrix[i][j] << "\t";
        }
        cout << matrix[i][m-1] << "]" << endl;
    }
    cout << "]" << endl; 
}

Python

import random
from sys import maxsize
from datetime import datetime

random.seed(datetime.now())
n = 10
m = 9
matrix = []
for i in range(n):
    matrix.append([random.randrange(maxsize) for j in range(m)])

print(matrix)

JS (Node.js)

var n = 10; 
var m = 9; 

n = 10
m = 9
matrix = [];
for(var i = 0; i < n; i++){
    matrix[i] = [];
    for(var j = 0; j < n; j++){
        matrix[i].push(Math.ceil( Math.random() * Number.MAX_SAFE_INTEGER ));
    }
}

console.log(matrix);

Go

package main

import "math/rand"
import "fmt"
import "time"

func main() {
	rand.Seed(time.Now().UTC().UnixNano())
	n := 10
	m := 9
	matrix := make([][]int, n)
	for i := 0; i < n; i++ {
		matrix[i] = make([]int, m)
		for j := 0; j < m; j++ {
			matrix[i][j] = rand.Int()
		}
	}
	fmt.Println(matrix)
}

Thanks for reading! If you notice any errors, possible optimisations, or have questions, hit me up on twitter @sMorac. Bear in mind that code still needs to be readable :).

If you want to find all the codes I've been using, here you go: https://github.com/sMorac/rand

Photo credit : Tim Evans