How to create a Motoko function to random sample a vector

I would like to develop a Motoko function to random sample a vector. It should look like:

let v: [Nat] = [1,2,3,4,5,6,8,9];
let vv: [Nat] = randomSample(sample=v, num_samples=4, with_repetition=false, seed=12);
// vv = [2,4,6,1];

Given a fixed seed and a sample vector, we should always return the same vector vv

Any hint on how should I proceed?

You can check out @Zenvoich’s fuzz library or the Random module in the base lib to generate the samples for the vv array.

2 Likes

Hi @tomijaga , It’s the first time I heard about the Motoko “on-chain” package manager “mops”. Is this the standard way to use existing Motoko packages?
I read also in the “mops” we page that I should install the base package using “mops”: mops add base but this is weird because the bas3e package was already available by default. Excuse me for diverting topic but I would like to use the fuzz package and this using mops is something new

Mops is the state of the art and a much better experience than vessel. As a community we likely need do some maintenance and get some of the classic packages in there, but I’m trying to publish anything new that I build there.

3 Likes

What about the “base” library, do I really nned to do “mops add base”?

Maybe you get base for free? I’m not sure…I think it may default to the latest version and add base for you. @ZenVoich would be able to clear that up.

2 Likes

By default, dfx uses the base package that comes with it.

If you set packtool in dfx.json, then dfx will not add the base package, but will leave it up to packtool.

So yes, if you want to use mops and you need base package, then you need to add it to mops.toml

2 Likes

I have installed mops and with it, the package fuzz. however, when I do dfx generate I get an error with the base library:

Stderr:
.mops/base@0.10.1/src/Text.mo:817.43-817.47: type error [M0072], field textLowercase does not exist in type ...

It seems that there is something inconsistent in the “mops” base library? perhaps I should delete something before doing dfx generate?

You need to install the most recent version of the motoko compiler (v0.10.1) that contains the textLowercase() function in the prim module and then update dfx to use the newly installed compiler.
Installing the mocv cli tool (also created by @ZenVoich ) and following the setup instructions should fix the issue.

2 Likes

If you want a permutation (i.e. no repetitions) then you need to some own code on top of fuzz. I don’t think that’s provided by fuzz or any other pseudo-random number library.

1 Like

You could push your selections into a Set until the desired number are found. There is likely a more efficient way, but depending on your use case, that would likely be the most compact using existing libraries.

1 Like