포트: 정책 성적표
Coddy의 C 개발자를 위한 Swift 코스 레슨. 48개 중 48번째.
챌린지
중급C 참조 구현을 포팅하세요. accepts(_ score: Int) -> Bool를 요구하는 ScoreRule을 구현하고, 최소값 이상의 점수를 허용하는 PassRule(minimum:)을 구현하세요. 변경 가능한 record(_ name: String, score: Int) -> Bool와 report(using rule: any ScoreRule) -> String을 갖는 값 형식 GradeBook()을 구현하세요. 0부터 100까지의 점수만 허용하고, 같은 이름의 이전 점수는 덮어쓰세요. 그 외의 점수는 변경 없이 거부하세요. 제공된 규칙이 허용하는 항목만 이름순으로 정렬해 공백으로 구분된 name:score 형식으로 보고하세요. 사용자 지정 규칙과 독립적인 복사본이 제대로 작동해야 합니다. 입력은 최소값(0부터 100까지)에 이어 최대 30개의 이름/점수 쌍으로 이루어집니다. 이름은 최대 10개의 소문자 ASCII 문자로 이루어진 단어이고, 점수는 -10부터 110까지입니다. 허용된 기록 작업의 개수를 출력하고, 보고 내용이 비어 있지 않을 때만 공백과 보고 내용을 이어서 출력하세요.
필수 API와 solve(_ input: String) -> String을 구현하세요. 마지막 개행 없이 출력 텍스트를 반환하고, 편집 가능한 코드에서 출력하지 마세요. 잠긴 드라이버는 추가적인 유효 입력으로 API를 별도로 확인한 다음, 반환된 텍스트를 정확히 한 개의 개행과 함께 출력합니다. 모든 숫자 연산은 Int 범위 안에서 이루어집니다.
C의 ScoreRule은 콜백과 컨텍스트 포인터를 결합하며 Swift 프로토콜로 바뀝니다. C의 GradeBook은 고정 용량 항목 배열을 인라인으로 저장하므로, 구조체를 대입하면 기록 값이 독립적으로 복사됩니다. 필수 Swift GradeBook은 구조체이며, 복사된 값은 독립적으로 변경되어야 합니다. C의 정책 컨텍스트는 보고 과정에서 실행되는 모든 콜백 중에도 유효하게 유지됩니다. 사용자 지정 정책을 지원할 수 있도록 각 점수에 대해 제공된 규칙을 호출하세요.
완성된 C 참조 프로그램입니다. 함께 표시된 세 개의 헤더 파일을 같은 위치에 두고 main.c를 컴파일하세요. 진입점은 main뿐입니다. 이 구현은 최종 포트를 위해 의도적으로 완성된 상태입니다.
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;
}
Swift API를 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 플레이그라운드