This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 10062 - Tell me the frequencies! | |
* Author: ~menon | |
***/ | |
#include <iostream> | |
#include <cstring> | |
#include <cstdio> | |
using namespace std; | |
struct data { | |
int cnt; | |
char ch; | |
}; | |
bool flag = false; | |
void calculateFrequency(char *s); | |
int main() | |
{ | |
char s[1005]; | |
//freopen("input.txt", "r", stdin); | |
while(gets(s)) | |
{ | |
calculateFrequency(s); | |
} | |
return 0; | |
} | |
void calculateFrequency(char *s) | |
{ | |
struct data myData[96]; | |
int counts[96]; | |
// set all the value of counts to 0; | |
memset(counts, 0, sizeof(counts)); | |
//counts frequency; | |
for(int i = 0; s[i]; i++) { | |
if(s[i] >= 32 && s[i] <= 128) { | |
counts[s[i] - 32]++; | |
} | |
} | |
// copy counts[] into myData[] structure; | |
for(int i = 0; i < 96; i++) { | |
myData[i].cnt = counts[i]; | |
myData[i].ch = i + 32; | |
} | |
// sort my structure accoding to condition; | |
struct data temp; | |
for (int i = 1; i < 96; i++) | |
for (int j = 0; j < 96 - i; j++) { | |
if (myData[j].cnt > myData[j + 1].cnt) { | |
temp = myData[j]; | |
myData[j] = myData[j + 1]; | |
myData[j + 1] = temp; | |
} | |
else if(myData[j].cnt == myData[j + 1].cnt) { | |
if(myData[j].ch < myData[j + 1].ch) { | |
temp = myData[j]; | |
myData[j] = myData[j + 1]; | |
myData[j + 1] = temp; | |
} | |
} | |
} | |
// this is for not printing any extra newline after output; | |
if(flag == true) { | |
printf("\n"); | |
} | |
flag = true; | |
// prnt sorted frequency; | |
for(int i = 0; i < 96; i++) { | |
if(myData[i].cnt) { | |
printf("%d %d\n", myData[i].ch, myData[i].cnt); | |
} | |
} | |
} |
Comments
Post a Comment