Menu
CoddyTech

Port: Policy Grade Book

Lesson 48 of 48 in Coddy's Swift for GDScript Developers course.

challenge icon

Challenge

Medium

Port the GDScript reference. Implement ScoreRule requiring accepts(_ score: Int) -> Bool, and PassRule(minimum:) accepting scores at least minimum. Implement value type GradeBook() with mutating record(_ name: String, score: Int) -> Bool and report(using rule: any ScoreRule) -> String. Accept scores 0 through 100; overwrite a previous score for the same name. Reject other scores without change. Report only entries accepted by the supplied rule, sorted by name, as space-separated name:score. Custom rules and independent copies must work. Input is minimum 0 through 100 followed by 0 through 30 name/score pairs. Names are lowercase ASCII words up to 10 letters; scores -10 through 110. Output count of accepted record operations, followed by a space and report only when nonempty.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Complete GDScript reference for the same input and output contract:

extends SceneTree
class PassRule:
    var minimum: int
    func _init(value: int):
        minimum = value
    func accepts(score: int) -> bool:
        return score >= minimum
class GradeBook:
    var _scores: Dictionary = {}
    func copy():
        var other = GradeBook.new()
        other._scores = _scores.duplicate()
        return other
    func record(name: String, score: int) -> bool:
        if score < 0 or score > 100:
            return false
        _scores[name] = score
        return true
    func report(rule) -> String:
        var names = _scores.keys()
        names.sort()
        var rows: Array[String] = []
        for name in names:
            if rule.accepts(_scores[name]):
                rows.append("%s:%d" % [name, _scores[name]])
        return " ".join(rows)
func read_tokens() -> Array[String]:
    var bytes = PackedByteArray()
    while true:
        var chunk = OS.read_buffer_from_stdin(4096)
        if chunk.is_empty():
            break
        bytes.append_array(chunk)
    var pattern = RegEx.new()
    pattern.compile("\\S+")
    var tokens: Array[String] = []
    for found in pattern.search_all(bytes.get_string_from_utf8()):
        tokens.append(found.get_string())
    return tokens
func _init():
    var tokens = read_tokens()
    var rule = PassRule.new(tokens[0].to_int())
    var book = GradeBook.new()
    var accepted = 0
    for index in range(1, tokens.size(), 2):
        if book.record(tokens[index], tokens[index + 1].to_int()):
            accepted += 1
    var report = book.report(rule)
    print(str(accepted) + (" " + report if not report.is_empty() else ""))
    quit()

Your code goes in ScoreRule.swift, PassRule.swift, GradeBook.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

The GDScript reference uses copy() and dictionary duplication to request independent score storage. Ordinary GDScript assignment aliases the same book. In Swift, GradeBook is a struct, so assignment must preserve independent value state. The GDScript policy call relies on the supplied object implementing accepts; Swift requires declared conformance. Both reports must call the supplied rule, including custom rules.

Try it yourself

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)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }

All lessons in Swift for GDScript Developers

Practice on your own: Swift playground