How to use Random

I’m trying to do something very simple. Generate a random number…
I can’t understand from the docs how to use it.
I read these docs here Random :: Internet Computer
But I get all kind of errors which I don’t really understand…
Can someone give me an example please?

Hi,

So in need for uuid I came with this. Not sure it’s what you need but hopefully it helps.

If you don’t need uuid word8ToText should work for you.

public func getBytes(n : Nat) : async [Word8] {
let m = (n + 31) / 32;
var chunk = Iter.fromArray();
let beacons = Array.init(m, chunk);
for (i in Iter.range(0, m - 1)) {
beacons[i] := (await Random.blob()).bytes();
};
let source = Iter.fromArrayMut(beacons);
Array.tabulate(n, func _ {
switch (chunk.next()) {
case (?x) x;
case (null) {
chunk := Option.unwrap(source.next());
Option.unwrap(chunk.next())
}
}
})
};

public func uuid() : async Text {
var uuid : Text = “”;
uuid #= Text.concat(word8ToText(await getBytes(2)) , “-”);
uuid #= Text.concat(word8ToText(await getBytes(2)) , “-”);
uuid #= Text.concat(word8ToText(await getBytes(2)) , “-”);
uuid #= Text.concat(word8ToText(await getBytes(2)) , “-”);
uuid #= word8ToText(await getBytes(6));

uuid;

};

private func word8ToText(i : [Word8]): Text {
var str: Text = “”;
Array.foldLeft<Word8, Text>(i, str, func(str, i) { Text.concat(str, Nat.toText(Prim.word8ToNat(i))) });
};

But I get all kind of errors which I don’t really understand…

Even if you get errors you don’t understand, it helps to include them in your post, in case others can make sense of them.

Seems like everytime I try to use 3 backticks to format the code I get a 403 forbidden…

I think it’s more the edit feature that’s broken?

because I can do this in a fresh post

I deleted my reply by mistake not sure how to revert it I will repost

I managed to get it working. I was confused about how to use the Finite class but it seems I get it now.

import Random "mo:base/Random";

actor {

    let r = Random.Finite("test");
    public func testRandom() : async ?Bool {
        return r.coin();
    }
}

Another question. is there anything like rand() from C or Random.nextFloat from java or Math.random() from javascript. My quest with Motoko Random started because I want to shuffle an array…

What does the return of this function look like?

a float between 0 and 1. Math.random() is using xorshift128+

I gave it a go here xorshift128plus.mo · GitHub
Seems to be generating pseudo random numbers but since I’m new Motoko learner I’m pretty sure it can be written better.