0

I am working on CS50 PSET2 Substitution and have passed all the checks, except the last one: "handles multiple duplicate characters in key." What I get is:

:( handles multiple duplicate characters in key
    timed out while waiting for program to exit

However, when I test the program with a key such as "aabbccddeeffgghhiijjkkllmm" the correct thing happens, and the program quits, printing "Key does not contain (only) one of each letter" as I wanted it to. See below:

substitution/ $ ./substitution aabbccddeeffgghhiijjkkllmm
Key does not contain (only) one of each letter

I have included my code below. Any thoughts on why I am getting this error? Thank you!

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

int main(int argc, string argv[])
{
    // Check if num of args is right
    if (argc != 2)
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }
    // Check that key is 26 chars
    else if (strlen(argv[1]) != 26)
    {
        printf("Key must contain 26 characters.\n");
        return 1;
    }

    // Check that key has one of each letter only
    int sum_letter_values = 0;

    for (int i = 0; i < 26; i++)
    {
        if (!isalpha(argv[1][i]))
        {
            printf("Key must contain only letters\n");
            return 1;
        }

        argv[1][i] = toupper(argv[1][i]);
        sum_letter_values += argv[1][i];
    }

    if (sum_letter_values != 2015)
    {
        printf("Key does not contain (only) one of each letter\n");
        return 1;
    }

    // Get and print out user input
    string user_input = get_string("plaintext: ");

    // Encrypt user input
    string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int input_length = strlen(user_input);
    for (int i = 0; i < input_length; i++)
    {
        int x = 0;
        int count = 0;
        while (x == 0)
        {
            if (!isalpha(user_input[i]))
            {
                x++;
            }
            if (user_input[i] == alphabet[count])
            {
                user_input[i] = argv[1][count];
                x++;
            }
            else if (user_input[i] == alphabet[count] + 32)
            {
                user_input[i] = argv[1][count] + 32;
                x++;
            }
            else
            {
                count++;
            }
        }
    }

    printf("ciphertext: %s\n", user_input);
}

1 Answer 1

0

It times out because the code that checks for duplicated letters is flawed. It's possible that the key can have a specific combination of duplicated letters that totals out correctly. The test case specifically checks for this by using one of those combinations.

Try running ./substitution MMCcEFGHIJKLMNOPQRqTUVWXeZ and see what your code does. ;-) It needs a rethink on how to check for duplicate letters explicitly.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .