*ฅ^•ﻌ•^ฅ* ✨✨  HWisnu's blog  ✨✨ о ฅ^•ﻌ•^ฅ

Generate random numbers

...

...

gen_randNum Function

Generates an array of random numbers within a specified range. It takes three parameters:

The function uses the std.rand.DefaultPrng type to generate random numbers and the std.heap.page_allocator type to allocate memory for the array. It returns the generated array or an error if the allocation fails.

const std        = @import("std");
const print      = std.debug.print;
const tMilli     = std.time.milliTimestamp;
const RandGen    = std.rand.DefaultPrng;
const PageAlloc  = std.heap.page_allocator;


fn gen_randNum(minVal: u32, maxVal: u32, arraySize: u32) ![]u32 {
    const seed = tMilli();
    var rnd = RandGen.init(@intCast(seed));
    const randNums = try PageAlloc.alloc(u32, arraySize);

    for (randNums) |*num| {
        num.* = rnd.random().intRangeAtMost(u32, minVal, maxVal);
    }
    return randNums;
}

main Function

Defines the parameters for generating random numbers and calls the gen_randNum function to generate the array. If the generation is successful, it prints the last 50 numbers in the array. If an error occurs, it prints the error message and exits the program.

Note: The ![]u32 return type of the gen_randNum function indicates that it may return an error. The try keyword is used to handle the error, and the |numbers| syntax is used to pattern-match the successful result.

pub fn main() void {

    const minVal: u32 = 1;
    const maxVal: u32 = 1_000;
    const arraySize: u32 =1_000;

    var randomNumbers: []u32 = undefined;
    if (gen_randNum(minVal, maxVal, arraySize)) |numbers| {
        randomNumbers = numbers[0..];
    } else |err| {
        print("Error generating random numbers: {}", .{err});
        return;
    }
    
    print("Unordered array:\n", .{});
    for (randomNumbers[randomNumbers.len - 50 ..]) |item| {
        print("{} ", .{item});
    }
}