#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define NUM_NUM 16

int compare(const void *a, const void *b) {
		return (*(int *)a - *(int *)b);
}

int findMax(int *tally) {
		int i, max;
		max = tally[0];
		for (i = 1; i < NUM_NUM; i++) 
				if (tally[i] > max) max = tally[i];
		return max;
}

int calculateModes(int *tally, int *mode) { //returns number of modes
		int i, max, modes;
		max = findMax(tally);
		modes = 0;
		for (i = 0; i < NUM_NUM; i++) if (max == tally[i]) mode[modes++] = i;
		return modes;
}

int kthDataValue(int *tally, int value) {
		int *sorted, fin;
		sorted = (int *)malloc(NUM_NUM * sizeof(int));
		memcpy(sorted, tally, NUM_NUM * sizeof(int));
		qsort(sorted, NUM_NUM, sizeof(int), compare);
		fin = sorted[value];
		free(sorted);
		return fin;
}

int main(int argc, char *argv[]) {
		int *array, *count, *mode, elements, i, modes, kth;
		FILE *out = fopen("tally8.txt","w");

		srand(time(0));
		printf("Number of elements? ");
		scanf("%d", &elements);
		array = (int *)malloc(elements * sizeof(int));
		count = (int *)malloc(NUM_NUM * sizeof(int));
		mode = (int *)malloc(NUM_NUM * sizeof(int));
		for (i = 0; i < elements; i++) array[i] = rand()%NUM_NUM;
		for (i = 0; i < NUM_NUM; i++) count[i] = 0;

		for (i = 0; i < elements; i++) count[array[i]]++;
		fprintf(out, "Value    ");
		for (i = 0; i < NUM_NUM; i++) fprintf(out, "\t%d",i);
		fprintf(out, "\nFrequency");
		for (i = 0; i < NUM_NUM; i++) fprintf(out, "\t%d", count[i]);
		fprintf(out, "\nThe most frequent number(s) show(s) up ");
		fprintf(out, "%d times.\n", findMax(count));
		modes = calculateModes(count, mode);
		fprintf(out, "The modes are:");
		for (i = 0; i < modes; i++) fprintf(out, "\t%d", mode[i]);
		printf("The kth data value you want is...? ");
		fprintf(out, "\nThe kth data value you want is...? ");
		scanf("%d", &kth);
		fprintf(out, "%d\n", kth);
		kth = kthDataValue(count, kth);
		fprintf(out, "\nThe kth data value was... %d!\n", kth);
		printf("The output is available in tally8.txt for your perusal.\n");

		free(mode);
		free(array);
		free(count);
		return 0;
}

