Snippet. Vala. Generate Random Number

Random numbers are very useful. For instance, to generate a verification code. To do this you may use the Vala Glib library and specifically the function Glib.Random.int_range. The function takes two arguments. The first one specifies the start of the range, and the second argument specifies the end of the range.

int random_number = Random.int_range(0,100);

Another option is to use the function string_number to generate a random string of specified length and containing only numbers. The generated numbers will differ from using the Glib.Random.int_range. The main difference is that the returned string may contain 0s at the beginning, unlike the Glib.Random.int_range.

Example

// Generate 10 random numbers 10 characters long
for(int i=0; i<10; i++){
    string random_number = string_random(10,"1234567890");
    stdout.printf(random_numbers + "\n");
}

Updated on: 23 Nov 2024