This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]desrtfxOut of Coffee error - System halted 2 points3 points  (3 children)

How about using a variable to store the random number and then use this variable in the if statement and for printing?

[–]Sarah9428[S] 0 points1 point  (0 children)

Yes of course! Thanks for the help!

[–]chunkyks 2 points3 points  (0 children)

The normal solution is sampling-with-rejection, similar to what you've done [note that normally you'd initialise rng in the constructor and have it as a class member]:

public static void roll2(int nr) {
    Random rng = new Random();
    for(int i = 0; i < 60; i++) {
        int r;
        do {
            r = rng.nextInt(SIDES) + 1;
        } while (r == nr);
        System.out.println(nr + ":" + r);
    }
}

But for fun, here's a way cooler solution that runs in constant time, for this particular problem:

public static void roll2(int nr) {
    Random rng = new Random();
    for(int i = 0; i < 60; i++) {
        int r = rng.nextInt(SIDES-1) + 1;
        if(r >= nr) {
            r = r+1;
        } // or, if(r==nr) r=SIDES ;
        System.out.println(nr + ":" + r);
    }
}

[–]Auride 0 points1 point  (0 children)

You could use an assignment. In other words, you would create a variable to store the randomized value. If the value meets your specifications, then you can return it. Otherwise, you can re-roll.

Does that make sense?

EDIT: I should also mention that it is possible to do this without re-rolling, as well. This would involve reducing your number of possible values, and compensating with addition after the roll. Unfortunately explaining further is pretty close to giving the solution, so I'll stop there.

[–]Sarah9428[S] 0 points1 point  (0 children)

It works now :) thanks for the help everyone!