bot50 2024-02-24 21:42:49 +00:00
commit 6dc338eb76
1 changed files with 74 additions and 0 deletions

74
substitution.c Normal file
View File

@ -0,0 +1,74 @@
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
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", key[plaintext[i] - 65]);
}
else
{
printf("%c", tolower(key[plaintext[i] - 97]));
}
}
else
{
printf("%c", plaintext[i]);
}
}
printf("\n");
}