// Arup Guha
// 4/29/2022
// Solution to Spring 2022 COP 3502 Final Exam Question 1

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

char* getBestName(char** possibleNames, int numNames);

int main(void) {

    // Get the # of names.
    int n, i;
    printf("how many names?\n");
    scanf("%d", &n);

    # Read them in.
    char** list = malloc(sizeof(char*)*n);
    for (i=0; i<n; i++) {
        char tmp[10000];
        scanf("%s", tmp);
        int len = strlen(tmp);
        list[i] = malloc(sizeof(char)*(len+1));
        strcpy(list[i], tmp);
    }

    # Call our function for our test.
    char* res = getBestName(list, n);
    printf("Winner winner chicken dinner: %s\n", res);

    # Free stuff.
    for (i=0; i<n; i++)
        free(list[i]);
    free(list);

    return 0;
}

# Returns a pointer to our best name from possibleNames which stores numNames names.
char* getBestName(char** possibleNames, int numNames) {

    // Assume the first answer is the best.
    int minLen = strlen(possibleNames[0]), i;
    char* res = possibleNames[0];

    // Loop through the rest.
    for (i=1; i<numNames; i++) {

        // The length of the current string.
        int newLen = strlen(possibleNames[i]);

        // Either this one's shorter, or it's the same length but comes first alphabetically...
        // for us to update.
        if (newLen < minLen || (newLen == minLen && strcmp(possibleNames[i], res) < 0)) {
            minLen = newLen;
            res = possibleNames[i];
        }
    }

    // Ta da!
    return res;
}
