COMP1400 – Programming for Designers

Class announcements for Programming for Designers

COMP1400 – Programming for Designers random header image

Week 8 Tut – Objects

Posted by on September 9th, 2012 · Lab
  1. Create an instance of the java.util.Random class in BlueJ using the Tools > Use Library Class… option.
  2. Right click on the object created to see its methods. Try running some of them. What do they do?
  3. Read the Java docs for the Random class.
  4. 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?
  5. 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.
  6. 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).

  7. Write a method selectRandom(String[] names) which returns a randomly selected name from the given array. Each name should be selected with equal probability.
  8. 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:

    1. {“Malcolm”, “Troy”, “Sim”}
    2. {“Malcolm”, “Sim”, “Troy”}
    3. {“Troy”, “Malcolm”, “Sim”}
    4. {“Troy”, “Sim”, “Malcolm”}
    5. {“Sim”, “Troy”, “Malcolm”}
    6. {“Sim”, “Malcolm”, “Troy”}

No Comments so far ↓

There are no comments yet...Kick things off by filling out the form below.

You must log in to post a comment.