Skip to content

Instantly share code, notes, and snippets.

@jordansinger
Created December 18, 2015 03:35
Show Gist options
  • Save jordansinger/69c1813b78944addb6c8 to your computer and use it in GitHub Desktop.
Save jordansinger/69c1813b78944addb6c8 to your computer and use it in GitHub Desktop.
ascii.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int NUMASCII = 127;
struct Ascii {
int code; // ascii character code
int occurrences; // number of occurrences
};
int swap(const void *a, const void *b) {
const struct Ascii *character1 = a;
const struct Ascii *character2 = b;
return character2->occurrences - character1->occurrences;
}
int main(int argc, char *args[]) {
struct Ascii ascii[NUMASCII];
int counter = 0;
for (struct Ascii *a = ascii; a < ascii + NUMASCII; a++) {
a->code = counter++;
a->occurrences = 0;
}
char c;
while((c = getchar()) != EOF) {
int code = c;
ascii[code].occurrences += 1;
}
qsort(ascii, NUMASCII, sizeof(*ascii), swap);
for (int i = 0; i < NUMASCII; ++i) {
if (ascii[i].occurrences > 0) {
printf("%c: %i\n", (char)ascii[i].code, ascii[i].occurrences);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment