Nimbin2git.christianimmanuel.de / Games / dvd / scoreword.c

dvd files

last change 2026-09-04 (2 hours ago)

wget https://git.christianimmanuel.de/games/dvd/archive/dvd.tar.gz
scoreword.c 2.2 KB · 64 lines raw
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

// Macro for calculating word value based on index
#define CALCULATE_WORD_VALUE(index) ((index <= 3) ? 100 : (index > 12 ? 5 : 100 - (95 * (index - 3) / 9)))

int calculateMatchScore(const char *query, const char *title) {
    int totalScore = 0;
    int wordCount = 0; // Count of query words
    int matchCount = 0; // Count of matched words

    // Copy query to a temporary buffer
    char *queryCopy = strdup(query);

    // Tokenize query into words
    char *queryWord = strtok(queryCopy, " ");
    while (queryWord) {
        wordCount++; // Count total words in query
        char *match = strstr(title, queryWord);
        if (match) {
            // Check the distance of the matching word in the title
            int position = match - title;
            int wordIndex = 0;

            // We want to take into account the position of the word in the title
            // More closely matched words should contribute more to the score
            if (position == 0 || *(match - 1) == ' ') {
                matchCount++;
                int distanceFactor = (position == 0) ? 100 : (100 - (position % 10));  // Reward closer matches

                // Add the score based on word index and position in title
                totalScore += CALCULATE_WORD_VALUE(matchCount) * distanceFactor / 100;
            }
        }
        queryWord = strtok(NULL, " ");
    }

    free(queryCopy);

    // Normalize the score: proportional to query words
    return wordCount > 0 ? (totalScore / wordCount) : 0;
}

int main() {
    const char *testCases[][2] = {
        {"a bc ac", "a bb c"},
        {"ad bc ac", "a bb c"},
        {"the last unicorn", "the last unicorn movie"},
        {"star wars", "the empire strikes back"},
        {"harry potter", "harry potter and the sorcerer's stone"},
        {"harry and potter", "harry potter and the sorcerer's stone"},
        {"the harry and potter", "harry potter and the sorcerer's stone"}
    };

    for (int i = 0; i < 7; i++) {
        const char *query = testCases[i][0];
        const char *title = testCases[i][1];
        int score = calculateMatchScore(query, title);
        printf("Query: \"%s\", Title: \"%s\" => Score: %d\n", query, title, score);
    }

    return 0;
}