Advertisement
dimipan80

12. Cards Frequencies

Sep 13th, 2014
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. /* We are given a sequence of N playing cards from a standard deck.
  2.  * The input consists of several cards (face + suit), separated by a space.
  3.  * Write a program to calculate and print at the console the frequency
  4.  * of each card face in format "card_face -> frequency".
  5.  * The frequency is calculated by the formula appearances / N
  6.  * and is expressed in percentages with exactly 2 digits after the decimal point.
  7.  * The card faces with their frequency should be printed in the order of the card face's
  8.  * first appearance in the input. The same card can appear multiple times in the input,
  9.  * but it's face should be listed only once in the output. */
  10.  
  11. import java.util.ArrayList;
  12. import java.util.HashMap;
  13. import java.util.Scanner;
  14.  
  15. public class _12_CardsFrequencies {
  16.  
  17.     public static void main(String[] args) {
  18.         // TODO Auto-generated method stub
  19.         Scanner scan = new Scanner(System.in);
  20.         System.out.println("Enter your Cards (face+suit) on single line, separated by a space:");
  21.         String inputLine = scan.nextLine();
  22.  
  23.         String[] inputCards = inputLine.split("[^0-9AJQK]+");
  24.  
  25.         HashMap<String, Integer> cardsFrequency = new HashMap<>();
  26.         for (String card : inputCards) {
  27.             Integer count = cardsFrequency.get(card);
  28.             if (count == null) {
  29.                 count = 0;
  30.             }
  31.  
  32.             cardsFrequency.put(card, count + 1);
  33.         }
  34.  
  35.         int allCards = inputCards.length;
  36.         ArrayList<String> printedCards = new ArrayList<>();
  37.         for (String key : inputCards) {
  38.             if (printedCards.contains(key)) {
  39.                 continue;
  40.             }
  41.             int times = cardsFrequency.get(key);
  42.             float frequency = ((float) times * 100) / allCards;
  43.             System.out.printf("%s -> %.2f", key, frequency);
  44.             System.out.println("%");
  45.             printedCards.add(key);
  46.         }
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement