Sulaiman Alyahya
Sulaiman Alyahya

Reputation: 347

Extend java.util.Random to control generation of numbers

Hello I have the following tasks:

First, I am given this code that uses a method to generate random numbers 100 times:

public class Q3 {
    public static void printDiceRolls(Random randGenerator) {

        for (int i = 0; i < 100; i++) {
            System.out.println(randGenerator.nextInt(6) + 1);
        }
    }

    public static void main(String[] args) {
        Random man = new Random();
        printDiceRolls(man);
    }
}

Second, I am asked to make a class LoadedDice that extends the Random class:

public class LoadedDice extends Random {
    // instance variables - replace the example below with your own
    public int nextInt(int num) {
        // code right here
        return 3;
    }
}

Then I am asked to override the public int nextInt ( int num ) and do the following

Override the public int nextInt(int num) method such that with a 50% chance, the new method always returns the largest number possible (i.e., num-1), and with a 50% chance, it returns what the Random's nextInt method would return

I do not quite understand what my overridden method should do in this case.

Suggestions?

Upvotes: 2

Views: 3134

Answers (4)

irreputable
irreputable

Reputation: 45433

if(super.nextBoolean())
    return num-1;
return super.nextInt(num);

if num<Integer.MAX/2, we can

int x = super.nextInt(num*2);
return Math.min(x, num-1);

Upvotes: 0

user2146562
user2146562

Reputation:

I guess one way to do this is to use (another?) random number generator with a uniform distribution and set it to return 0 or 1. The 0/1 would be the 50% for you to make your decision upon.... either returning super.nextInt or the max number.

Upvotes: 1

Garrett Hall
Garrett Hall

Reputation: 30022

Use another Random instance to give you a 50% chance (e.g. nextInt(100) >= 50) then based on that return a constant or a real random.

Upvotes: 1

Onikoroshi
Onikoroshi

Reputation: 303

To me, it looks like the nextInt(int) function comes up with a number between 1 and the input. In the root Random class, this function finds a random number within that range. What they want you to do is change that so that half the time it will return a random number in the range, but the other half the time it will give the maximum number.

In the example they gave, you're rolling a dice, so the range is 1-6. Normally, nextInt will find a random number between 1 and 6. But your new function will only do that half the time. The other half the time, it will return 6.

I have an idea on how you can implement that, but it seems like it would be cheating to go that far. ^^;

Upvotes: 0

Related Questions