diff options
Diffstat (limited to '25_break_encr/breaker.c')
-rw-r--r-- | 25_break_encr/breaker.c | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/25_break_encr/breaker.c b/25_break_encr/breaker.c new file mode 100644 index 0000000..1f71d2c --- /dev/null +++ b/25_break_encr/breaker.c @@ -0,0 +1,56 @@ +#include <stdio.h> +#include <stdlib.h> +#include <ctype.h> + +size_t max(int * letters, size_t n) { + int maxCount = letters[0]; + int maxElementIndex = 0; + + for (size_t i = 1; i < n; i++) { + if (letters[i] > maxCount) { + maxCount = letters[i]; + maxElementIndex = i; + } + } + return maxElementIndex; +} + +int decrypt(FILE * f) { + int c; + int letters[26] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + while ((c = fgetc(f)) != EOF) { + if (isalpha(c)) { + c = tolower(c); + c -= 'a'; + letters[c] = letters[c] + 1; + } + } + + size_t maxElement = max(letters, 26); + int ans; + + if (maxElement >= 4) { + ans = maxElement - 4; + } else { + ans = 26 - (4 - maxElement); + } + return ans; +} + +int main(int argc, char ** argv) { + if (argc != 2) { + fprintf(stderr,"Usage: breaker inputFileName\n"); + return EXIT_FAILURE; + } + + FILE * f = fopen(argv[1], "r"); + if (f == NULL) { + perror("Could not open file"); + return EXIT_FAILURE; + } + size_t key = decrypt(f); + + printf("%d\n", key); + + return EXIT_SUCCESS; +} |