Menu
CoddyTech

포팅: 재고 명령어

Coddy의 C++ 개발자를 위한 Swift 코스 레슨. 48개 중 47번째.

challenge icon

챌린지

중급

C++ 참조 구현을 Swift로 포팅하세요. Inventory()에 add(_ name: String, count: Int) -> Bool, take(_ name: String, count: Int) -> Bool, quantity(of name: String) -> Int, report() -> String를 구현하세요. add는 양수 개수만 허용합니다. take는 양수이면서 현재 재고 이하인 개수만 허용합니다. 거부된 요청은 상태를 변경하지 않으며, 존재하지 않는 항목의 수량은 0입니다. 성공적으로 take한 뒤에도 재고가 0인 항목을 유지합니다. 저장된 모든 이름을 오름차순으로 나열하고, 각 항목은 name:quantity 형식으로 공백으로 구분해 보고하세요. 입력에는 0개에서 40개 사이의 명령 트리플이 포함됩니다. 명령은 add name count 또는 take name count입니다. 이름은 최대 10글자의 소문자 ASCII 단어이고, 개수는 -10에서 100까지입니다. 성공한 명령의 개수를 출력하고, 보고 내용이 비어 있지 않은 경우에만 그 뒤에 공백과 보고 내용을 출력하세요.

필수 API와 solve(_ input: String) -> String을 구현하세요. 마지막 개행 없이 출력 텍스트를 반환하고, 편집 가능한 코드에서 출력하지 마세요. 잠금 처리된 드라이버는 추가 유효 입력으로 API를 별도로 검사한 다음, 반환된 텍스트를 정확히 한 개의 개행과 함께 출력합니다. 모든 숫자 연산은 Int 범위 안에서 이루어집니다.

C++ 참조 구현은 클래스 값 내부에 정렬된 맵을 소유합니다. 그 값에 대한 참조는 상태를 공유하지만, 맵을 소유한 객체를 복사하면 독립된 값이 생성됩니다. Swift 구현에서도 요청이 거부될 때 상태를 변경하지 않고 재고가 0인 항목을 유지하세요.

명시된 입력/출력 규약을 위한 완전한 C++ 참조 구현입니다. 이 동작을 필수 Swift 파일에 포팅하세요:

#include <iostream>
#include <string>
#include <map>
#include <sstream>
class Inventory {
    std::map<std::string, int> quantities;
public:
    int quantity(const std::string &name) const {
        auto found = quantities.find(name);
        return found == quantities.end() ? 0 : found->second;
    }
    bool add(const std::string &name, int count) {
        if (count <= 0) return false;
        quantities[name] = quantity(name) + count;
        return true;
    }
    bool take(const std::string &name, int count) {
        int available = quantity(name);
        if (count <= 0 || count > available) return false;
        quantities[name] = available - count;
        return true;
    }
    std::string report() const {
        std::ostringstream output;
        bool first = true;
        for (const auto &[name, value] : quantities) {
            if (!first) output << ' ';
            first = false;
            output << name << ':' << value;
        }
        return output.str();
    }
};
int main() {
    Inventory inventory;
    std::string command, name;
    int count, accepted = 0;
    while (std::cin >> command >> name >> count) {
        bool ok = command == "add" ? inventory.add(name, count) : inventory.take(name, count);
        if (ok) ++accepted;
    }
    std::string report = inventory.report();
    std::cout << accepted;
    if (!report.empty()) std::cout << ' ' << report;
    std::cout << '\n';
}

코드는 Inventory.swift, Functions.swift에 작성하세요. main.swift에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.

직접 해보기

import Foundation
func apiChecks(_ input: String) -> Bool {
let x = Inventory(); guard x.quantity(of: "missing") == 0 && !x.take("missing", count: 1) && x.report().isEmpty else { return false }; guard x.add("oak", count: 4) && !x.take("oak", count: 5) && !x.add("oak", count: 0) && x.quantity(of: "oak") == 4 else { return false }; return x.take("oak", count: 4) && x.report() == "oak:0" && !x.take("oak", count: -1) && Inventory().report().isEmpty
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// PUBLIC API 검사 시작
let apiOK = apiChecks(input)
// PUBLIC API 검사 끝
if apiOK { print(solve(input)) } else { print("API mismatch") }

C++ 개발자를 위한 Swift의 모든 레슨

직접 연습해 보세요: Swift 플레이그라운드