Advertisement
dimipan80

Cards Frequencies

Nov 13th, 2014
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a JavaScript function findCardFrequency(str) that that accepts the following parameters:
  2.  string of several cards (face + suit), separated by a space. The function calculates and prints at the console
  3.  the frequency of each card face in format "card_face -> frequency". The frequency is calculated by
  4.  the formula appearances / N and is expressed in percentages with exactly 2 digits after the decimal point.
  5.  The card faces with their frequency should be printed in the order of the card face's first appearance
  6.  in the input. The same card can appear multiple times in the input, but its face should be listed only once
  7.  in the output. Write JS program cardFrequencies.js that invokes your function with the sample input data below
  8.  and prints the output at the console. */
  9.  
  10. "use strict";
  11.  
  12. function findCardFrequency(str) {
  13.     var cardFacesArr = str.split(/\W+/).filter(Boolean);
  14.     var cardsFrequencies = {};
  15.     for (var i = 0; i < cardFacesArr.length; i += 1) {
  16.         var card = cardFacesArr[i];
  17.         if (!(cardsFrequencies.hasOwnProperty(card))) {
  18.             cardsFrequencies[card] = 0;
  19.         }
  20.         cardsFrequencies[card]++;
  21.     }
  22.  
  23.     function calculateCurrentCardFrequencyInPercentages(appearance) {
  24.         var frequency = appearance * 100 / cardFacesArr.length;
  25.         return frequency.toFixed(2);
  26.     }
  27.  
  28.     for (i = 0; i < cardFacesArr.length; i += 1) {
  29.         card = cardFacesArr[i];
  30.         if (cardsFrequencies.hasOwnProperty(card) && cardsFrequencies[card]) {
  31.             var cardFrequency = calculateCurrentCardFrequencyInPercentages(cardsFrequencies[card]);
  32.             console.log("%s -> %s%", card, cardFrequency);
  33.             cardsFrequencies[card] = false;
  34.         }
  35.     }
  36. }
  37.  
  38. findCardFrequency('8♥ 2♣ 4♦ 10♦ J♥ A♠ K♦ 10♥ K♠ K♦');
  39. console.log();
  40. findCardFrequency('J♥ 2♣ 2♦ 2♥ 2♦ 2♠ 2♦ J♥ 2♠');
  41. console.log();
  42. findCardFrequency('10♣ 10♥');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement