When I use the playground on the official website to run

`import Random "mo:base/Random";`

It will prompt this error, is it because of a version problem?

btw, which Homie knows how to use Random, can anyone provide some code examples?

When I use the playground on the official website to run

`import Random "mo:base/Random";`

It will prompt this error, is it because of a version problem?

btw, which Homie knows how to use Random, can anyone provide some code examples?

`Random`

depend on the `raw_rand`

system API, which is not implemented in the interpreter, so you are getting an `assertion failure`

.

You can check this example for random usage: examples/motoko/random_maze at master · dfinity/examples · GitHub

1 Like

Hi @chenyan

Thanks for your reply, I have a question, please help.

I know that the range of the return value in rangeFrom is determined by the parameter p, the return value of rangeFrom: [0 … 2^p-1], if p is 3, then the range of the random number is [0…8].

If the random number range I want to obtain is [0…99] or [5…10], how should I determine this parameter p first.For example, I expect to get a random number from 0 to 99, but I need to know what p is first.

Thanks

I think this code should almost do what you want:

(or set p to be the binary logarithm of the range, draw a number, if in range, return it + mix, otherwise reject and try again)

Hey @claudio , I am trying to get a random number between [0…`max`

) according to the code example you sent me.

But when I call the getMax function, the returned result is (opt 0). Is there any solution?

This is my code, thanks

```
func bit(b : Bool) : Nat {
if (b) 1 else 0;
};
func chooseMax(f : Random.Finite, max : Nat) : ? Nat {
assert max > 0;
do ? {
if (max == 1) return ? 0;
var k = bit(f.coin()!);
var n = max / 2;
while (n > 1) {
k := k * 2 + bit(f.coin()!);
n := n / 2;
};
if (k < max)
return ? k
else chooseMax(f, max) !; // retry
};
};
public func getMax(max:Nat):async ?Nat{
let entropy = await Random.blob();
var f = Random.Finite(entropy);
var result= chooseMax(f,max);
return result;
};
```