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
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
int** count_chars(char *s) | |
{ | |
int **counts = (int**)malloc(256 * sizeof(int) * sizeof(char)); | |
int i; | |
for(i = 0; i < 256; i++) | |
{ | |
counts[i] = (int*)malloc(sizeof(int)*2); | |
counts[i][0] = i; | |
counts[i][1] = 0; | |
} | |
while(*s) | |
{ | |
counts[(int)*s][1] += 1; | |
s++; | |
} | |
return counts; | |
} | |
int int_pair_asc(const void *a, const void *b){ | |
int *first = *(int**)a; | |
int *second = *(int**)b; | |
return first[1] - second[1]; | |
} | |
int int_pair_desc(const void *a, const void *b){ | |
return (int_pair_asc(a, b) * -1); | |
} | |
int main(){ | |
char msg[] = "I am a large brown bear who lives in the forest. My diet consists primarily of honey and spaceships."; | |
printf("string: '%s'\n", msg); | |
int **counts = count_chars(msg); | |
qsort(counts, 256, sizeof(int), int_pair_desc); | |
int i; | |
for(i = 0; i < 256; i++){ | |
if(counts[i][1] > 0) | |
printf("Rank[%d]: '%c' - %d\n", i+1, counts[i][0], counts[i][1]); | |
} | |
return 0; | |
} |
No comments:
Post a Comment