Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* We are given a sequence of N playing cards from a standard deck.
- * The input consists of several cards (face + suit), separated by a space.
- * Write a program to calculate and print at the console the frequency
- * of each card face in format "card_face -> frequency".
- * The frequency is calculated by the formula appearances / N
- * and is expressed in percentages with exactly 2 digits after the decimal point.
- * The card faces with their frequency should be printed in the order of the card face's
- * first appearance in the input. The same card can appear multiple times in the input,
- * but it's face should be listed only once in the output. */
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Scanner;
- public class _12_CardsFrequencies {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scan = new Scanner(System.in);
- System.out.println("Enter your Cards (face+suit) on single line, separated by a space:");
- String inputLine = scan.nextLine();
- String[] inputCards = inputLine.split("[^0-9AJQK]+");
- HashMap<String, Integer> cardsFrequency = new HashMap<>();
- for (String card : inputCards) {
- Integer count = cardsFrequency.get(card);
- if (count == null) {
- count = 0;
- }
- cardsFrequency.put(card, count + 1);
- }
- int allCards = inputCards.length;
- ArrayList<String> printedCards = new ArrayList<>();
- for (String key : inputCards) {
- if (printedCards.contains(key)) {
- continue;
- }
- int times = cardsFrequency.get(key);
- float frequency = ((float) times * 100) / allCards;
- System.out.printf("%s -> %.2f", key, frequency);
- System.out.println("%");
- printedCards.add(key);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement