process_guess

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.8 kB
2
Indexable
Never
char *verify(char *userGuess, char *answer)
{
    /*
     * Used to process the user guess and compare with the chosen random word
     * arg1: userGuess - The user's guess
     * arg2: answer - The randomly chosen answer for a particular Wordle session
     *
     * Returns: 0 - On running out of guesses without correctly guessing the answer
     *          1 - On correctly guessing the answer within the max number of
     *              guesses. Done by checking if all characters in the intermediate
     *              representation of the string are uppercase (i.e. all letters are in
     *              their correct positions)
     */
    char *lowerCaseGuess = str_to_lower(userGuess);
    char *lowerCaseAnswer = str_to_lower(answer);

    /* intermediate string is of the form --A--, aPp-- etc.
        it is declared as a char array instead of a char pointer because a char array can
        be modified, but a char pointer cannot be. Max length is defined
    */
    char intermediateString[MAX_LEN];

    // initially all characteres in intermediateString are '-'s
    for (int i = 0; i < MAX_LEN; i++)
    {
        intermediateString[i] = '-';
    }

    int *intermediateChecks = malloc((len + 1) * sizeof(int));

    // initially all checks are 0 (false) as no guess has been made yet
    for (int i = 0; i < len; i++)
    {
        intermediateChecks[i] = 0;
    }

    // first run, check all correct placed characters
    for (int i = 0; i < len; i++)
    {
        if (lowerCaseGuess[i] == lowerCaseAnswer[i])
        {
            char uppercaseChar = (char)toupper((int)lowerCaseGuess[i]);
            intermediateString[i] = uppercaseChar;
            intermediateChecks[i] = 1;
        }
    }

    // second run, check existing characters but in different places
    for (int i = 0; i < len; i++)
    {
        if (intermediateString[i] == '-')
        {
            // no exact match
            for (int j = 0; j < len; j++)
            {
                if (lowerCaseGuess[i] == lowerCaseAnswer[j] && !intermediateChecks[j])
                {
                    intermediateString[i] = (char)tolower((int)lowerCaseGuess[i]);
                    // break from inner loop once a different location match is found
                    break;
                }
            }
        }
    }

    char *resultString = malloc((len + 1) * sizeof(char));

    for (int i = 0; i < len; i++)
    {
        // printf("%c", intermediateString[i]);
        resultString[i] = intermediateString[i];
    }
    resultString[len] = '\0';
    // printf("\n");

    free(lowerCaseGuess);
    free(lowerCaseAnswer);
    free(intermediateChecks);
    // return all_uppercase(intermediateString, len);
    return resultString;
}