From 710bf56689085ae8904389f29c10a22fa4f582f1 Mon Sep 17 00:00:00 2001 From: bot50 Date: Sat, 24 Feb 2024 21:46:31 +0000 Subject: [PATCH] kukemuna-cs50/problems/2024/x/substitution@20240224T214631.295295947Z --- substitution.c | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 substitution.c diff --git a/substitution.c b/substitution.c new file mode 100644 index 0000000..ebda538 --- /dev/null +++ b/substitution.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include + +int validate_key(string key); // NQXPOMAFTRHLZGECYJIUWSKDVB +void substitute(string plaintext, string key); + +int main(int argc, string argv[]) +{ + // Print usage and exit if argc is not 2 or key is not integer + if (argc != 2 || validate_key(argv[1]) > 0) + { + printf("Usage: ./substitution key\n"); + return 1; + } + else + { + string key = argv[1]; + string plaintext = get_string("plaintext: "); + substitute(plaintext, key); + } + return 0; +} + +// Convert a string of numbers to integer +int validate_key(string key) +{ + // Sum of consecutive numbers: (b + a) x (b - a + 1) / 2 + // If key length is 26 then iterate each string element + if (strlen(key) == 26) + { + int sum = 0; + + for (int i = 0; i < strlen(key); i++) + { + if (isalpha(key[i])) + { + sum += toupper(key[i]); + } + } + + if (sum == 2015) // Sum of 26 unique uppercase characters + { + return 0; + } + } + return 1; +} + +void substitute(string plaintext, string key) +{ + printf("ciphertext: "); + + for (int i = 0; i < strlen(plaintext); i++) + { + if (isalpha(plaintext[i])) + { + if (isupper(plaintext[i])) + { + printf("%c", toupper(key[plaintext[i] - 65])); + } + else + { + printf("%c", tolower(key[plaintext[i] - 97])); + } + } + else + { + printf("%c", plaintext[i]); + } + } + printf("\n"); +}