移植:策略成绩簿
Coddy 面向 C++ 开发者的 Swift 课程 课程的第 48 课,共 48 课。
挑战
中等移植 C++ 参考实现。实现 ScoreRule,要求提供 accepts(_ score: Int) -> Bool,并实现 PassRule(minimum:),接受分数至少为 minimum 的成绩。实现值类型 GradeBook(),包含可变方法 record(_ name: String, score: Int) -> Bool 和 report(using rule: any ScoreRule) -> String。接受 0 到 100 的分数;同一姓名的新分数会覆盖之前的分数。其他分数会被拒绝,且不产生任何变化。报告中只包含由传入规则接受的条目,按姓名排序,并以空格分隔,格式为 name:score。自定义规则和相互独立的副本都必须正常工作。输入为 0 到 100 的最低分,后接 0 到 30 组姓名和分数。姓名是最多 10 个字母的小写 ASCII 单词;分数范围为 -10 到 110。输出接受的记录操作数;仅当报告非空时,再输出一个空格和报告内容。
实现所需的 API 和 solve(_ input: String) -> String。返回不带末尾换行符的输出文本;不要在可编辑代码中打印。锁定的驱动程序会使用其他有效输入独立检查这些 API,然后输出返回的文本,并且只添加一个换行符。所有数值运算都不会超出 Int 的范围。
C++ 的 GradeBook 按值持有自己的映射,因此普通复制会复制映射条目,副本之间的状态变化互不影响。抽象的 ScoreRule 引用可通过虚派发支持调用方自定义规则。在 Swift 中,请使用所需的值类型,并接受任何符合协议的评分规则。
下面是符合上述输入输出约定的完整 C++ 参考实现。请将此行为移植到指定的 Swift 文件中:
#include <iostream>
#include <string>
#include <map>
#include <sstream>
struct ScoreRule {
virtual bool accepts(int score) const = 0;
virtual ~ScoreRule() = default;
};
class PassRule final : public ScoreRule {
int minimum;
public:
explicit PassRule(int minimum) : minimum(minimum) {}
bool accepts(int score) const override { return score >= minimum; }
};
class GradeBook {
std::map<std::string, int> scores;
public:
bool record(const std::string &name, int score) {
if (score < 0 || score > 100) return false;
scores[name] = score;
return true;
}
std::string report(const ScoreRule &rule) const {
std::ostringstream output;
bool first = true;
for (const auto &[name, score] : scores) {
if (!rule.accepts(score)) continue;
if (!first) output << ' ';
first = false;
output << name << ':' << score;
}
return output.str();
}
};
int main() {
int minimum;
if (!(std::cin >> minimum)) return 0;
PassRule rule(minimum);
GradeBook book;
std::string name;
int score, accepted = 0;
while (std::cin >> name >> score) if (book.record(name, score)) ++accepted;
std::string report = book.report(rule);
std::cout << accepted;
if (!report.empty()) std::cout << ' ' << report;
std::cout << '\n';
}
你的代码应写在 ScoreRule.swift、PassRule.swift、GradeBook.swift 和 Functions.swift 中。main.swift 包含提供的输入输出代码,不能编辑。
亲手试试
import Foundation
func apiChecks(_ input: String) -> Bool {
struct ProbeRule: ScoreRule { func accepts(_ score: Int) -> Bool { score % 2 == 0 } }
var b = GradeBook(); guard b.record("a", score: 40) && b.record("b", score: 71) && !b.record("a", score: 101) else { return false }; var copy = b; _ = copy.record("a", score: 88); return b.report(using: ProbeRule()) == "a:40" && copy.report(using: ProbeRule()) == "a:88" && b.report(using: PassRule(minimum: 40)) == "a:40 b:71" && PassRule(minimum: 50).accepts(50)
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 开始公开 API 检查
let apiOK = apiChecks(input)
// 结束公开 API 检查
if apiOK { print(solve(input)) } else { print("API mismatch") }
面向 C++ 开发者的 Swift 课程中的所有课
自己练习: Swift 在线编辑器