0

我试图找出如何列出得分最高的单词,基于这个函数来计算分数,这些单词来自一个单词数组,左右。我该如何解决这个问题?

4

2 回答 2

4

由于您只需要分数最高的单词,因此无需跟踪所有候选单词的分数。跟踪最好的就足够了。

string best_word;
int best_score = 0;
for (auto word &: all_the_words) {
    int cur_score = ScrabbleScore(word);
    if (cur_score > best_score) {
        best_word = word;
        best_score = cur_score;
    }
}
// Now you have best_word and best_score.

编辑:扩展以处理具有相同最佳分数的所有单词。

vector<string> best_words;
int best_score = 0;
for (auto word &: all_the_words) {
    int cur_score = ScrabbleScore(word);
    if (cur_score > best_score) {
        best_words.clear();
        best_words.push_back(word);
        best_score = cur_score;
    } else if (cur_score == best_score) {
        best_words.push_back(word);
    }
}
// Now you have best_words and best_score.
于 2013-09-24T17:37:18.547 回答
1

您可以将您的单词字符串放在 a 中std::vector<std::string>,然后在该向量上调用std::sort()算法,指定自定义比较函数以按单词的“分数”对单词进行排序。

有关详细信息,请参阅以下示例代码:

#include <algorithm>    // for std::sort
#include <exception>    // for std::exception
#include <iostream>     // for std::cout
#include <stdexcept>    // for std::runtime_error
#include <string>       // for std::string
#include <vector>       // for std::vector
using namespace std;

// NOTE #1: Since this function is *observing* the "word" parameter,
// pass it by const reference (const string & word).
int ScrabbleScore(const string & word) {
    int score = 0;
    static const char scoreTable[26] = { 
        1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 
        5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 
        1, 4, 4, 8, 4, 10 
    };

    for (auto letter : word) {
        // if alphabet word
        if (letter >= 'a' && letter <= 'z') {
            score += scoreTable[letter - 'a'];
        } else {
            // NOTE #2: Throw an exception when an invalid
            // letter is found.
            throw runtime_error("Invalid letter in word.");
        }
    }   
    return score;
}

int main() {
    // Some test words
    vector<string> words = {
        "hi", "hello", "world", "ciao",
        "integer", "sum", "sort", "words"
    };

    // Sort vector by ScrabbleScore (descending order)
    sort(words.begin(), words.end(), 
        [](const string& lhs, const string& rhs) {
            return ScrabbleScore(lhs) > ScrabbleScore(rhs);
        }
    );

    // Print result
    cout << "<word> (<score>)" << endl;
    cout << "------------------" << endl;
    for (const auto & w : words) {
        cout << w << " (" << ScrabbleScore(w) << ")" << endl;
    }
}

输出:

<word> (<score>)
------------------
world (9)
words (9)
hello (8)
integer (8)
ciao (6)
hi (5)
sum (5)
sort (4)
于 2013-09-24T17:45:57.853 回答