Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Course: Software University - Javascript Basics
- //Topic: Loops, Arrays and Strings
- //Homework: Problem 16. Card Frequencies
- //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.
- function findCardFrequency(str){
- var arrOfCards = str.split(" ");
- var faces = [];
- var count = {};
- var result = "";
- for (var i = 0; i<arrOfCards.length; i++){
- if (arrOfCards[i].length == 2){
- faces.push(arrOfCards[i].substring(0,1));
- } else {
- faces.push(arrOfCards[i].substring(0,2));
- }
- }
- for (var j = 0; j<faces.length; j++){
- if (count[faces[j]] == null){
- count[faces[j]] = 1;
- } else {
- count[faces[j]] ++;
- }
- }
- for (var k=0; k < Object.keys(count).length; k++){
- result += faces[k] + " -> " + ((count[faces[k]]*100)/faces.length).toFixed(2) + " % \n";
- }
- return result.trimRight();
- }
- findCardFrequency('8♥ 2♣ 4♦ 10♦ J♥ A♠ K♦ 10♥ K♠ K♦');
- findCardFrequency('J♥ 2♣ 2♦ 2♥ 2♦ 2♠ 2♦ J♥ 2♠');
- findCardFrequency('10♣ 10♥');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement