commit 3cde7259a8956cde2fcf80a6000b45b2000e314e Author: bot50 Date: Sun Feb 25 09:57:34 2024 +0000 kukemuna-cs50/problems/2024/x/substitution@20240225T095734.427910511Z diff --git a/substitution.c b/substitution.c new file mode 100644 index 0000000..4732453 --- /dev/null +++ b/substitution.c @@ -0,0 +1,78 @@ +#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 (char c = 'A'; c <= 'Z'; c++) + { + for (int i = 0; i < 26; i++) + { + if (toupper(key[i]) == c) + { + sum++; + break; + } + } + } + + if (sum == 26) // Sum of 26 unique uppercase characters, but also MMCcEFGHIJKLMNOPQRqTUVWXeZ + { + 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"); +}