Menu
CoddyTech

Port: Policy Grade Book

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

challenge icon

Challenge

Medium

Port the C 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.

The C ScoreRule combines a callback with a context pointer and becomes a Swift protocol. The C GradeBook stores fixed-capacity entry arrays inline, so struct assignment copies its record values independently. The required Swift GradeBook is a struct whose copied value must evolve independently. The C policy context remains valid for every callback during reporting. Call the supplied rule for each score so custom policies remain supported.

Complete C reference program. Compile main.c with the three shown headers beside it; main is the only entry point. The implementation is intentionally complete for this final port.

score_rule.h

#ifndef SCORE_RULE_H
#define SCORE_RULE_H
#include <stdbool.h>
typedef struct { const void *context; bool (*accepts)(const void *, int); } ScoreRule;
#endif

pass_rule.h

#ifndef PASS_RULE_H
#define PASS_RULE_H
#include "score_rule.h"
typedef struct { int minimum; } PassRule;
static bool pass_accepts(const void *context, int score) {
    return score >= ((const PassRule *)context)->minimum;
}
#endif

grade_book.h

#ifndef GRADE_BOOK_H
#define GRADE_BOOK_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "score_rule.h"
typedef struct { char name[11]; int score; } Grade;
typedef struct { Grade grades[30]; int size; } GradeBook;
static bool grade_book_record(GradeBook *book, const char *name, int score) {
    if (score < 0 || score > 100) return false;
    int index = 0;
    while (index < book->size && strcmp(book->grades[index].name, name) != 0) ++index;
    if (index == book->size) {
        strcpy(book->grades[index].name, name);
        ++book->size;
    }
    book->grades[index].score = score;
    return true;
}
static int grade_compare(const void *left, const void *right) {
    return strcmp(((const Grade *)left)->name, ((const Grade *)right)->name);
}
static void grade_book_report(const GradeBook *book, ScoreRule rule, char output[1024]) {
    Grade sorted[30];
    memcpy(sorted, book->grades, (size_t)book->size * sizeof(Grade));
    qsort(sorted, (size_t)book->size, sizeof(Grade), grade_compare);
    size_t used = 0;
    output[0] = '\0';
    for (int i = 0; i < book->size; ++i) {
        if (!rule.accepts(rule.context, sorted[i].score)) continue;
        used += (size_t)snprintf(output + used, 1024 - used, "%s%s:%d", used ? " " : "", sorted[i].name, sorted[i].score);
    }
}
#endif

main.c

#include "pass_rule.h"
#include "grade_book.h"
int main(void) {
    PassRule policy;
    if (scanf("%d", &policy.minimum) != 1) return 0;
    ScoreRule rule = {&policy, pass_accepts};
    GradeBook book = {0};
    char name[11], report[1024];
    int score, accepted = 0;
    while (scanf("%10s %d", name, &score) == 2)
        if (grade_book_record(&book, name, score)) ++accepted;
    grade_book_report(&book, rule, report);
    printf("%d%s%s\n", accepted, report[0] ? " " : "", report);
    return 0;
}

Implement the Swift APIs in ScoreRule.swift, PassRule.swift, GradeBook.swift, Functions.swift. Keep the supplied main.swift driver.

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 C Developers

Practice on your own: Swift playground