如何列出得分最高的单词

时间:2013-09-24 17:18:23

标签: c++

我正在尝试找出如何列出具有最高分数的单词,基于此函数来计算分数,单词来自一组单词,或者左右。我该如何解决这个问题?

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:1)

您可以将单词字符串放在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)