Menu
CoddyTech

최종: 인벤토리 포트

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

challenge icon

챌린지

쉬움

C++ 참조 구현을 포팅하세요. 입력은 단어들이며, 알파벳순으로 정렬된 word=count 쌍을 쉼표로 연결해 반환하고, 단어가 없으면 none을 반환합니다. 단어는 소문자 ASCII이며, 중복 단어도 각각 셉니다. 호출자의 입력을 변경하지 마세요.

입력은 stdin으로 전달되는 하나의 JSON 배열입니다. 수정할 수 없도록 잠긴 main은 이를 파싱하고, 공개 API를 호출한 다음 반환된 텍스트 앞에 result=를 붙여 출력하고 줄바꿈합니다. 헬퍼는 아무것도 출력하면 안 됩니다. 입력 사례를 처리하기 전에 독립적인 고정 프로브로 필수 API 동작을 확인하며, 구현 방식은 검사하지 않습니다.

완전한 C++ 참조 구현입니다. 이 파일들을 함께 저장하고 C++20으로 main.cpp를 컴파일하세요. 헤더는 헬퍼 API를 제공하며, main은 동일한 JSON 배열을 읽고 동일한 결과 프로토콜로 출력합니다. 표준 라이브러리만 사용합니다.

C++ 파일 inventory.hpp:

#pragma once
#include <map>
#include <string>
#include <vector>
inline std::string summarize(const std::vector<std::string> &words) {
    std::map<std::string,std::size_t> counts;
    for (const auto &word:words) ++counts[word];
    std::string out;
    for (const auto &[word,count]:counts) {
        if (!out.empty()) out+=',';
        out+=word+'='+std::to_string(count);
    }
    return out.empty()?"none":out;
}

C++ 파일 main.cpp:

#include <iostream>
#include <iterator>
#include <stdexcept>
#include "inventory.hpp"
class WordsJson {
    const std::string &text;
    std::size_t at=0;
    char peek() const { return at<text.size()?text[at]:'\0'; }
    char take() { if(at==text.size()) throw std::runtime_error("unexpected end"); return text[at++]; }
    void space() { while(peek()==' ' || peek()=='\n' || peek()=='\r' || peek()=='\t') ++at; }
    static int hex(char c) {
        if(c>='0' && c<='9') return c-'0';
        if(c>='a' && c<='f') return c-'a'+10;
        if(c>='A' && c<='F') return c-'A'+10;
        throw std::runtime_error("invalid escape");
    }
    std::string word() {
        if(take()!='"') throw std::runtime_error("expected string");
        std::string out;
        while(peek()!='"') {
            unsigned value=static_cast<unsigned char>(take());
            if(value=='\\') {
                if(take()!='u') throw std::runtime_error("expected Unicode escape");
                value=0;
                for(int i=0;i<4;++i) value=value*16+hex(take());
            }
            if(value<'a' || value>'z') throw std::runtime_error("expected lowercase ASCII word");
            out+=static_cast<char>(value);
        }
        take(); return out;
    }
public:
    explicit WordsJson(const std::string &input):text(input) {}
    std::vector<std::string> parse() {
        space(); if(take()!='[') throw std::runtime_error("expected array");
        space(); std::vector<std::string> words;
        if(peek()!=']') {
            for(;;) {
                words.push_back(word()); space();
                if(peek()==']') break;
                if(take()!=',') throw std::runtime_error("expected comma");
                space();
            }
        }
        take(); space();
        if(at!=text.size()) throw std::runtime_error("trailing input");
        return words;
    }
};
int main() {
    std::string text{std::istreambuf_iterator<char>(std::cin),std::istreambuf_iterator<char>()};
    auto words=WordsJson(text).parse();
    std::cout << "result=" << summarize(words) << '\n';
}

코드는 exercise.gd에 작성하세요. main.gd에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다. 각 class_name 형식은 이름에 맞는 파일에 두세요.

직접 해보기

extends Node

func contract_ok(data: Array) -> bool:

	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))

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

직접 연습해 보세요: 온라인 GDScript 컴파일러