Skip to content

Instantly share code, notes, and snippets.

@tangrs
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangrs/9364076 to your computer and use it in GitHub Desktop.
Save tangrs/9364076 to your computer and use it in GitHub Desktop.
/* gcc -O3 -Wall -Werror homework.c -o homework */
/* Accepts input from stdin. echo "Input String" | homework */
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char element_t;
/* Sort order doesn't really matter */
static int sort_compare(const void *_a, const void *_b) {
element_t a, b;
a = *(element_t *)_a;
b = *(element_t *)_b;
if (a == b)
return 0;
return (a < b) ? -1 : 1;
}
/* Replace with a sort function of your choice */
static void sort(element_t *arr, size_t number) {
qsort(arr, number, sizeof(*arr), sort_compare);
}
#define CHUNK_COUNT 16
int main() {
element_t c;
element_t *arr;
size_t i, count, repeat_count;
count = 0;
arr = NULL;
/* Read CHUNK_COUNT elements in at a time */
while (1) {
size_t read;
/* No NULL check - we got memory 'kay */
arr = realloc(arr, (count + CHUNK_COUNT) * sizeof(*arr));
read = fread(arr + count, sizeof(*arr), CHUNK_COUNT, stdin);
count += read;
if (read < CHUNK_COUNT)
break;
}
printf("[*] Finished reading. Number of elements: %ld\n", count);
/* Sort elements */
sort(arr, count);
printf("[*] Finished sorting\n");
/* Step through and count - worst case O(n) */
c = '\0';
repeat_count = 0;
for (i=0; i<count; i++) {
if (arr[i] != c) {
c = arr[i];
repeat_count = 0;
}
if (++repeat_count > count / 2)
break;
}
printf("[*] Finished counting\n");
if (repeat_count > count / 2) {
printf("[*] Element %#02x repeats more than %ld times\n",
c, count / 2);
} else {
printf("[*] No element repeats more than %ld times\n",
count / 2);
}
free(arr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment