Posted by Tim Wiley on September 10th, 2012 · Labs
- Create an instance of the
java.util.Random
class in BlueJ using the Tools > Use Library Class… option.
- Right click on the object created to see its methods. Try running some of them. What do they do?
- Read the Java docs for the Random class.
- Which method would you use to:
- Simulate a fair coin toss?
- Simulate a (six-sided) dice roll? What about ten-sided? Twenty-sided?
- Simulate a biased coin that shows heads 67% of the time?
- Open the Code Pad and do the following
- Write a command to construct a Random object with the seed 200 and assign it to a variable.
- Call nextInt() several times on the object you created.
- Create a second object with the same seed and call nextInt() on it too. Explain the result.
- Write a method
rollDice(int number, int nSides)
which returns the total result of rolling the number
dice with nSides
sides.
So for example rollDice(3, 6)
should return the result of rolling 3 six-sided dice (adding to a number between 3 and 18 inclusive).
- Write a method
selectRandom(String[] names)
which returns a randomly selected name from the given array. Each name should be selected with equal probability.
- Challenge: Write a method
shuffle(String[] names)
which takes an array of names are returns a copy of the list with the names randomly rearranged. Each possible should be returned with equal probability
So for instance, given the code:
String[] names = {"Malcolm", "Troy", "Sim"};
String[] shuffled = shuffle(names);
The following return values should be equally likely:
- {“Malcolm”, “Troy”, “Sim”}
- {“Malcolm”, “Sim”, “Troy”}
- {“Troy”, “Malcolm”, “Sim”}
- {“Troy”, “Sim”, “Malcolm”}
- {“Sim”, “Troy”, “Malcolm”}
- {“Sim”, “Malcolm”, “Troy”}
No Comments so far ↓
Comments are closed.