Thursday 25 August 2016

Chapter 7 Exercise 24, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

**7.24 (Simulation: coupon collector’s problem) Coupon collector is a classic statistics problem with many practical applications. The problem is to pick objects from a set of objects repeatedly and find out how many picks are needed for all the objects to be picked at least once. A variation of the problem is to pick cards from a shuffled deck of 52 cards repeatedly and find out how many picks are needed before you see one of each suit. Assume a picked card is placed back in the deck before picking another. Write a program to simulate the number of picks needed to get four cards from each suit and display the four cards picked (it is possible a card may be picked twice).
Here is a sample run of the program:

Queen of Spades
5 of Clubs
Queen of Hearts
 4 of Diamonds
Number of picks: 12 



public class ProgrammingEx7_24 {
 // Approach: Pick card at ramdom and check for suit then record if a suit
 // has been picked up. Keep doing that until all suits are picked up .
 
 public static void main(String[] args) {
 
  int mask = 0b1111, picked = 0b0000;
  int numberOfPick = 0;
  while ((mask & picked) != mask) {
   int card = pickCard();
   String suit = getSuit(card);
   int temp = picked;
   switch (suit) {
   case "Clubs":
    picked |= 0b1000;
    break;
   case "Diamonds":
    picked |= 0b0100;
    break;
   case "Hearts":
    picked |= 0b0010;
    break;
   case "Spades":
    picked |= 0b0001;
    break;
   }
 
   String rank = getRank(card);
 
   if (temp != picked) {
    System.out.println(rank + " of " + suit);
   }
   numberOfPick++;
 
  }
 
  System.out.println("Number of picks:" + numberOfPick);
 }
 
 public static int pickCard() {
  int card = (int) (Math.random() * 52.0); // pick a card 0-51
  return card;
 }
 
 public static String getRank(int card) {
 
  int rank = card / 4; // determine the rank 0-12
 
  String strRank = "";
 
  switch (rank) {
  case 0:
   strRank = "Ace";
   break;
  case 10:
   strRank = "Jack";
   break;
  case 11:
   strRank = "Queen";
   break;
  case 12:
   strRank = "King";
   break;
  default:
   strRank = "" + (rank + 1);
   break;
  }
 
  return strRank;
 
 }
 
 public static String getSuit(int card) {
 
  int suit = card % 4; // determine the suit 0-3
  String strSuit = "";
 
  switch (suit) {
  case 0:
   strSuit = "Clubs";
   break;
  case 1:
   strSuit = "Diamonds";
   break;
  case 2:
   strSuit = "Hearts";
   break;
  case 3:
   strSuit = "Spades";
   break;
  }
  return strSuit;
 
 }
 
}

No comments :

Post a Comment