Skip to content

Commit df0cc46

Browse files
authored
bugfix: random maze example
Fix broken implementation of `chooseMax` (courtesy of Timo Hanke)
1 parent 4f84bf4 commit df0cc46

File tree

1 file changed

+7
-9
lines changed
  • motoko/random_maze/src/random_maze

1 file changed

+7
-9
lines changed

motoko/random_maze/src/random_maze/Main.mo

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -41,16 +41,14 @@ actor {
4141
func chooseMax(f : Random.Finite, max : Nat) : ? Nat {
4242
assert max > 0;
4343
do ? {
44-
if (max == 1) return ? 0;
45-
var k = bit(f.coin()!);
46-
var n = max / 2;
47-
while (n > 1) {
48-
k := k * 2 + bit(f.coin()!);
49-
n := n / 2;
44+
var n = max - 1 : Nat;
45+
var k = 0;
46+
while (n != 0) {
47+
k *= 2;
48+
k += bit(f.coin()!);
49+
n /= 2;
5050
};
51-
if (k < max)
52-
return ? k
53-
else chooseMax(f, max) !; // retry
51+
if (k < max) k else chooseMax(f, max)!;
5452
};
5553
};
5654

0 commit comments

Comments
 (0)