如何列出得分最高的单词
How to list the word with the highest score
我正在尝试找出如何列出得分最高的单词,基于此函数来计算分数,单词来自单词数组,左右。我该如何解决这个问题?
由于您只需要得分最高的单词,因此无需跟踪所有候选单词的分数。跟踪最好的就足够了。
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.
您可以将单词字符串放在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)
相关文章:
- 文本文件中的单词链表
- 递归列出所有目录中的C++与Python与Ruby的性能
- 在指针的帮助下,文本文件中单词的频率
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何根据单词在文本中出现的概率输出单词
- Python中的for循环与C++有何不同
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 如何用for循环在c++中生成单词三角形
- 将数字转换为单词
- 使用if-else将数字转换为单词
- C++-字符串是否包含一个带有简单循环的单词
- 使用单词"not"作为C ++类的名称会导致VS2019错误
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- 如何在CPP的给定目录中列出UTF编码的文件名?
- C++为一串单词添加空格
- 如何根据其长度和分数列出比例最高的单词
- 列出不带元音的单词时出错
- 如何列出得分最高的单词