Advertisement
VKNikov

findCardFrequency

Jul 27th, 2014
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Created by VKNikov on 26.7.2014 г..
  3.  */
  4.  
  5. //Problem 16.   Cards Frequencies
  6. //Write a JavaScript function findCardFrequency(value) that that accepts the following parameters: array of several
  7. // cards (face + suit), separated by a space. The function calculates and prints at the console the frequency of
  8. // each card face in format "card_face -> frequency". The frequency is calculated by the formula appearances / N and is
  9. // expressed in percentages with exactly 2 digits after the decimal point. The card faces with their frequency
  10. // should be printed in the order of the card face's first appearance in the input. The same card can appear multiple
  11. // times in the input, but its face should be listed only once in the output. Write JS program cardFrequencies.js that
  12. // invokes your function with the sample input data below and prints the output at the console.
  13.  
  14. console.log('This script takes an array of several cards and prints the frequency of each card face.');
  15. console.log();
  16.  
  17. function findCardFrequency(arr) {
  18.     "use strict";
  19.  
  20.     var splittedInput = arr.split(/ /g);
  21.     var n = splittedInput.length;
  22.     var container = {};
  23.  
  24.     //This loop checks whether a card is present in the container and if not puts it there as key, the value stores
  25.     // the number of times the card is present in the input.
  26.     for (var i = 0; i < n; i++) {
  27.         var character = splittedInput[i].charAt(0);
  28.         if (!(character in container)) {
  29.             container[character] = 1;
  30.         } else {
  31.             container[character] += 1;
  32.         }
  33.     }
  34.  
  35.     //This loop calculates the ratio of every single card in the input and prints it on the console in percents. Note
  36.     //that it does not print the cards from the container but from the input array.
  37.     for (var i = 0; i < n; i++) {
  38.         var character = splittedInput[i].charAt(0);
  39.         if ((character in container)) {
  40.             if (character == 1) {
  41.                 console.log(character + '0 -> ' + (container[character]/n * 100).toFixed(2) + '%');
  42.             } else {
  43.                 console.log(character + ' -> ' + (container[character]/n * 100).toFixed(2) + '%');
  44.             }
  45.             delete container[character];
  46.         }
  47.     }
  48. }
  49.  
  50. findCardFrequency('8♥ 2♣ 4♦ 10♦ J♥ A♠ K♦ 10♥ K♠ K♦');
  51. findCardFrequency('J♥ 2♣ 2♦ 2♥ 2♦ 2♠ 2♦ J♥ 2♠');
  52. findCardFrequency('10♣ 10♥');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement