Random Numbers in TypeScript

Here’s the translation of the Go code to TypeScript, along with explanations in Markdown format suitable for Hugo:

// TypeScript's Math object provides pseudorandom number generation.

// For example, Math.random() returns a random number between 0 and 1.
console.log(Math.floor(Math.random() * 100) + ',' + Math.floor(Math.random() * 100));

// Math.random() returns a number f, 0.0 <= f < 1.0.
console.log(Math.random());

// This can be used to generate random numbers in other ranges,
// for example 5.0 <= f' < 10.0.
console.log((Math.random() * 5) + 5 + ',' + (Math.random() * 5) + 5);

// If you want a known seed, you can use a custom random number generator.
// Here's a simple implementation of a linear congruential generator:
class CustomRandom {
    private m: number = 2**32;
    private a: number = 1664525;
    private c: number = 1013904223;
    private seed: number;

    constructor(seed: number) {
        this.seed = seed;
    }

    next(): number {
        this.seed = (this.a * this.seed + this.c) % this.m;
        return this.seed / this.m;
    }

    intN(n: number): number {
        return Math.floor(this.next() * n);
    }
}

const r2 = new CustomRandom(42);
console.log(r2.intN(100) + ',' + r2.intN(100));

const r3 = new CustomRandom(42);
console.log(r3.intN(100) + ',' + r3.intN(100));

This TypeScript code demonstrates how to generate random numbers. Here’s a breakdown of what’s happening:

  1. We use Math.random() to generate random numbers between 0 and 1.

  2. To get random integers between 0 and 99, we multiply the result of Math.random() by 100 and use Math.floor() to round down.

  3. We show how to generate random numbers in a specific range, like between 5 and 10.

  4. Since TypeScript (and JavaScript) don’t have built-in support for seeded random number generation, we implement a simple linear congruential generator to demonstrate the concept of reproducible random numbers.

  5. We create two instances of our custom random number generator with the same seed to show that they produce the same sequence of numbers.

To run this TypeScript code, you would typically compile it to JavaScript and then run it with Node.js. Here’s an example of what the output might look like:

$ tsc random-numbers.ts
$ node random-numbers.js
23,84
0.123456789
7.1234,6.5678
88,36
88,36

Note that the actual numbers will be different each time you run the program, except for the last two lines which use the seeded custom random number generator.

For more advanced random number generation in TypeScript, you might want to consider using a library like seedrandom which provides more robust implementations of seeded random number generators.