// Jade Bowyer
// 9/7/2020
// Helper code for CIS 3362 Homework 2 Problem 3
// Finds Index of Coincidence for potential bins of letters

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

int main() {
	int i, j, k, length;
	char ciphertext[1000];

	//user inputs the ciphertext
	printf("Enter the ciphertext:\n");
	scanf("%s", ciphertext);
	length = strlen(ciphertext);

    //iterates through loose range of key lengths
	printf("Key\tIC\n");
	for (k = 1; k < 20; k++) {
		int freq[k][26];
		int size[k];

        //initializes bins' frequency arrays
		for (i = 0; i < k; i++)
			for (j = 0; j < 26; j++)
				freq[i][j] = 0;

        //initializes bins' size arrays
		int div = length/k, r = length%k;
		for (i = 0; i < k; i++)
			size[i] = div;
		if (r != 0)
			for (i = 0; i < r; i++)
				size[i]++;

        //populates bins' frequency arrays
		for (i = 0; i < length; i++)
			freq[i%k][ciphertext[i]-'a']++;

        //calculates sum of bins' ICs
		double IC = 0;
		for (i = 0; i < k; i++) {
			int top = 0, bottom = size[i]*(size[i]-1);
			for (j = 0; j < 26; j++)
				top += freq[i][j] * (freq[i][j]-1);
			IC += ((double)top)/bottom;
		}

		//averages out IC over all bins
		IC /= k;

		//printings results
		printf("%d\t%lf\n", k, IC);
	}

	return 0;
}
