Can this random function be made more meaningfully efficient?

Hello everyone,

I’ve recently launched a fun little betting game with a Minesweeper-like format on partyhats.xyz!

In each game, a user selects how many mines they want to play with (the more mines, the riskier). To set up the game board, I generate a random boolean array of size 25, where true represents a mine and false represents an empty cell. It works fine, but I am trying to figure out how to optimize it. I use random.byte() to get numbers 0–255, then modulo 25 to map them to indices 0–24. To avoid modulo bias, I discard values ≥250, ensuring each board position has an equal chance of containing a mine.

Can this be made more efficient? Thank you in advance for any suggestions!

Here’s the snippet of code I use to generate the mines:

  private func generateMines(mines : Nat) : async Result.Result<T.MinesArrayType, Text> {
    if (mines > 10 or mines < 1) {
      return #err("Invalid number of mines. Please choose between 1 and 10.");
    };

    let newMines = Array.init<Bool>(25, false);
    let seed = await Random.blob();
    let random = Random.Finite(seed);
    var count : Nat = 0;

    while (count < mines) {
      switch (random.byte()) {
        case (null) {
          return #err("Ran out of entropy while generating mines");
        };
        case (?value) {
          var randomByte = Nat8.toNat(value);
          if (randomByte < 250) {
            let index = randomByte % 25;
            if (not newMines[index]) {
              newMines[index] := true;
              count += 1;
            };
          };
          // If randomByte >= 250, discard and continue the loop
        };
      };
    };

    let mineArray = Array.freeze<Bool>(newMines);
    let args = {
      mineArray;
    };
    return #ok(args);
  };
1 Like