Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a JavaScript function findCardFrequency(str) that that accepts the following parameters:
- string of several cards (face + suit), separated by a space. The function calculates and prints 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 its face should be listed only once
- in the output. Write JS program cardFrequencies.js that invokes your function with the sample input data below
- and prints the output at the console. */
- "use strict";
- function findCardFrequency(str) {
- var cardFacesArr = str.split(/\W+/).filter(Boolean);
- var cardsFrequencies = {};
- for (var i = 0; i < cardFacesArr.length; i += 1) {
- var card = cardFacesArr[i];
- if (!(cardsFrequencies.hasOwnProperty(card))) {
- cardsFrequencies[card] = 0;
- }
- cardsFrequencies[card]++;
- }
- function calculateCurrentCardFrequencyInPercentages(appearance) {
- var frequency = appearance * 100 / cardFacesArr.length;
- return frequency.toFixed(2);
- }
- for (i = 0; i < cardFacesArr.length; i += 1) {
- card = cardFacesArr[i];
- if (cardsFrequencies.hasOwnProperty(card) && cardsFrequencies[card]) {
- var cardFrequency = calculateCurrentCardFrequencyInPercentages(cardsFrequencies[card]);
- console.log("%s -> %s%", card, cardFrequency);
- cardsFrequencies[card] = false;
- }
- }
- }
- findCardFrequency('8♥ 2♣ 4♦ 10♦ J♥ A♠ K♦ 10♥ K♠ K♦');
- console.log();
- findCardFrequency('J♥ 2♣ 2♦ 2♥ 2♦ 2♠ 2♦ J♥ 2♠');
- console.log();
- findCardFrequency('10♣ 10♥');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement