mardi 30 mai 2023

I am trying to set an upper bounds for a random int generator independant of the maximum value set in the generator itself

The idea is that I can set the max value to 15 or 25 but if the die only has 20 sides it shouldn't roll higher than 20.

I am creating a die roller as a personal project. I created a Dice object that takes in the size of the die (how many sides) as well as the minimum and maximum values that can be rolled on the die. I was having a problem where the on a 20 sided die, if i set the maximum over 20 it would roll higher than 20. I fixed this issue by implementing a do while loop that runs until the random value produces is less than the size of the die.

This seems wildly inefficient to me as theoretically it could run for hours just getting incorrect values again and again. I am looking for a more efficient solution.

//Main.java
public class Main {

    public static void main(String[] args) {

        MinMaxDice d20 = new MinMaxDice(20, 10, 20);
        System.out.println("\nThere are " + d20.sides + " sides on this die.");
        System.out.println("The max is " + d20.max + " and the min is " + d20.min + ".");
        for (int i = 0; i < 20; i++) {
            System.out.println("It rolled a " + d20.rollDie() + ".");
        }
    }
}

//MinMaxDice.java
import java.util.concurrent.ThreadLocalRandom;

public class MinMaxDice extends Dice {
    int max;
    int min;

    MinMaxDice(int sides, int min, int max) {
        super(sides);
        this.max = max;
        this.min = min;
    }

    public int rollDie() {
        int result;
        do {
            result = this.min + ThreadLocalRandom.current().nextInt(this.max - (this.min - 1));
        } while (result > sides);
        return result;
    }
}



Aucun commentaire:

Enregistrer un commentaire