Advertisement
VKNikov

Generate Random Hands of 5 cards

May 22nd, 2014
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.HashSet;
  3. import java.util.List;
  4. import java.util.Random;
  5. import java.util.Scanner;
  6. import java.util.Set;
  7.  
  8. //Problem 6. Random Hands of 5 Cards
  9. //Write a program to generate n random hands of 5 different cards form a standard suit of 52 cards.
  10.  
  11. public class _06_Random_Hands_Of_5_Cards {
  12.  
  13.     public static void main(String[] args) {
  14.         System.out.println("This program generates a random hands of 5 different cards(from 53 total).");
  15.         System.out.println("Please enter how many different hands do you want to be printed:");
  16.         Scanner input = new Scanner(System.in);
  17.         int numberOfHands = input.nextInt();
  18.        
  19.         Random rnd = new Random();
  20.         String [] cards = {"2","3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
  21.         String[] suits = {"♣", "♦", "♥", "♠"};
  22.        
  23.         //Populates the hashset with "random" cards.
  24.         for (int i = 0; i < numberOfHands; i++) {
  25.             Set<String> hand = new HashSet();
  26.             boolean fullSet = false;
  27.             while (!fullSet) {
  28.                 int randomCard = rnd.nextInt(13);
  29.                 int randomSuit = rnd.nextInt(3);
  30.                 hand.add(cards[randomCard] + suits[randomSuit]);
  31.  
  32.                 if (hand.size() == 5) {
  33.                     fullSet = true;
  34.                 }
  35.             }
  36.             //Prints the hand
  37.             for (String string : hand) {
  38.                 System.out.print(string + " ");
  39.             }
  40.             System.out.println();
  41.         }
  42.     }
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement