I’m trying to shuffle an array and I’m not sure what is the right way with Motoko.
This is what I have so far:
func shuffle(cards:[Card]) : [Card] {
var currentIndex = cards.size();
while(0 != currentIndex) {
var randomIndex = Float.toInt(Float.floor(Math.random() * Float.fromInt(currentIndex)));
currentIndex -= 1;
var tempValue = cards[currentIndex];
cards[currentIndex] := cards[randomIndex];
cards[randomIndex] := tempValue;
D.print(debug_show(randomIndex));
D.print(debug_show(currentIndex));
D.print(debug_show(tempValue.id));
};
return cards;
};
and I’m getting these errors:
Stderr:
main.mo:24.9-24.50: type error [M0073], expected mutable assignment target
main.mo:25.15-25.26: type error [M0096], expression of type
Int
cannot produce expected type
Nat
main.mo:25.9-25.40: type error [M0073], expected mutable assignment target
It seems I don’t know how to replace assign new values to array items and also it seems that the index of an array needs to be a Nat but I have no clue how to convert an Int to a Nat…
Math.random() generates pseudo random Floats between 0 and 1.