// 演算法 / Algorithm:
// 對每個單字累加字元權重，sum % 26 得到 0..25，再用 'z'-value 反向對應成字母。
// For each word, sum its letter weights, take % 26, then map via 'z'-value (reverse order).
// 結果字串長度 = 單字數量，需動態配置記憶體回傳 / result length = number of words; malloc it.

char* mapWords(char** words, int wordsSize, int* weights, int weightsSize) {
    // 配置 wordsSize+1 個位元組：每個單字一個字元，加上結尾的 '\0'
    // Allocate wordsSize+1 bytes: one char per word, plus the terminating '\0'.
    char* result = (char*)malloc((wordsSize + 1) * sizeof(char));

    // 外層迴圈：處理第 i 個單字 / outer loop: handle the i-th word
    for (int i = 0; i < wordsSize; i++) {
        int sum = 0;                       // 這個單字的權重總和歸零 / reset this word's weight sum

        // 內層迴圈：走過單字的每個字元，直到遇到字串結尾 '\0'
        // Inner loop: walk each char of the word until the '\0' terminator.
        for (int j = 0; words[i][j] != '\0'; j++) {
            char c = words[i][j];          // 取出當前字元 / current character
            // c - 'a' 把字母轉成 0..25 的索引，再去 weights 查權重並累加
            // c - 'a' turns the letter into an index 0..25; look up its weight and add it.
            sum += weights[c - 'a'];
        }

        int value = sum % 26;              // 摺疊進 0..25 範圍 / fold into range 0..25
        // 'z' - value：value=0 -> 'z'，value=25 -> 'a'，正好是反向字母順序
        // 'z' - value: value 0 -> 'z', value 25 -> 'a' — exactly reverse alphabetical order.
        result[i] = (char)('z' - value);
    }

    result[wordsSize] = '\0';              // C 字串必須以 '\0' 結尾 / C strings must end with '\0'
    return result;                         // 回傳；呼叫端負責 free / caller is responsible for free
}
