포팅: 정책 성적부
Coddy의 C# 개발자를 위한 Swift 코스 레슨. 48개 중 48번째.
챌린지
중급C# 참조 구현을 포팅하세요. ScoreRule을 구현하여 accepts(_ score: Int) -> Bool을 요구하고, 최소값 이상인 점수를 허용하는 PassRule(minimum:)을 구현하세요. 변경 가능한 record(_ name: String, score: Int) -> Bool과 report(using rule: any ScoreRule) -> String을 가진 값 형식 GradeBook()을 구현하세요. 0부터 100까지의 점수를 허용하고, 같은 이름의 기존 점수는 덮어쓰세요. 그 외의 점수는 상태를 변경하지 않고 거부하세요. 제공된 규칙이 허용하는 항목만 이름순으로 정렬하여 공백으로 구분된 name:score 형식으로 보고하세요. 사용자 지정 규칙과 독립적인 복사본이 작동해야 합니다. 입력은 0부터 100까지의 최소값 뒤에 0~30개의 이름/점수 쌍이 이어집니다. 이름은 최대 10자의 소문자 ASCII 단어이고, 점수 범위는 -10부터 110까지입니다. 허용된 기록 작업의 수를 출력하고, 보고 내용이 비어 있지 않을 때만 공백과 보고 내용을 이어서 출력하세요.
필수 API와 solve(_ input: String) -> String을 구현하세요. 마지막 개행 문자가 없는 출력 텍스트를 반환하고, 편집 가능한 코드에서 출력하지 마세요. 잠금된 드라이버는 추가 유효 입력으로 API를 독립적으로 검사한 다음, 반환된 텍스트를 정확히 한 개의 개행 문자와 함께 출력합니다. 모든 숫자 연산은 Int의 범위 내에서 이루어집니다.
C# 구조체는 성공적으로 쓸 때마다 비공개 딕셔너리를 교체하므로 복사한 책은 서로 독립적으로 유지됩니다. 일반적인 구조체 대입만으로는 딕셔너리 참조가 얕은 복사됩니다. Swift에서는 필수 값 형식을 사용하고, 규칙을 준수하는 모든 점수 규칙을 허용하세요.
명시된 입력/출력 계약에 대한 완전한 C# 참조 구현입니다. 이 동작을 필수 Swift 파일로 포팅하세요:
using System;
using System.Collections.Generic;
using System.Linq;
public interface IScoreRule
{
bool Accepts(int score);
}
public sealed class PassRule : IScoreRule
{
private readonly int minimum;
public PassRule(int minimum) { this.minimum = minimum; }
public bool Accepts(int score) { return score >= minimum; }
}
public struct GradeBook
{
// A struct copy initially shares this dictionary reference. Record replaces
// it with a fresh dictionary before writing, preserving independent values.
private SortedDictionary<string, int> scores;
public bool Record(string name, int score)
{
if (score < 0 || score > 100) return false;
var next = scores == null
? new SortedDictionary<string, int>(StringComparer.Ordinal)
: new SortedDictionary<string, int>(scores, StringComparer.Ordinal);
next[name] = score;
scores = next;
return true;
}
public string Report(IScoreRule rule)
{
if (scores == null) return "";
return string.Join(" ", scores.Where(pair => rule.Accepts(pair.Value))
.Select(pair => pair.Key + ":" + pair.Value));
}
}
public static class Program
{
public static void Main()
{
string[] tokens = Console.In.ReadToEnd().Split(
(char[])null, StringSplitOptions.RemoveEmptyEntries);
var rule = new PassRule(int.Parse(tokens[0]));
var book = new GradeBook();
int accepted = 0;
for (int i = 1; i < tokens.Length; i += 2)
if (book.Record(tokens[i], int.Parse(tokens[i + 1]))) accepted += 1;
string report = book.Report(rule);
Console.WriteLine(accepted + (report.Length == 0 ? "" : " " + report));
}
}코드는 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 플레이그라운드