Menu
CoddyTech

Cuối cùng: cổng kiểm kê

Bài học 47 trên 48 trong khóa học GDScript dành cho nhà phát triển C++ của Coddy.

challenge icon

Thử thách

Dễ

Chuyển đổi mã tham chiếu C++: nhận đầu vào là các từ, trả về các cặp word=count được sắp xếp theo thứ tự bảng chữ cái và nối với nhau bằng dấu phẩy, hoặc "none". Các từ là ký tự ASCII viết thường, các từ trùng lặp được đếm riêng. Không thay đổi đầu vào của bên gọi.

Đầu vào là một mảng (array) JSON trên stdin. Tệp main bị khóa sẽ phân tích nó, gọi các API công khai và in ra "result=" theo sau bởi văn bản được trả về và một ký tự dòng mới. Không có hàm trợ giúp nào được in ra. Các bộ kiểm tra độc lập sẽ xác minh hành vi API bắt buộc trước test case đầu vào; chúng không áp đặt phong cách triển khai.

Mã tham chiếu C++ đầy đủ. Lưu các tệp này cùng nhau và biên dịch (compile) main.cpp với C++20. Các tệp tiêu đề cung cấp các API trợ giúp; main đọc cùng một mảng JSON và in ra cùng một giao thức kết quả. Chỉ sử dụng thư viện (library) chuẩn.

Tệp 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;
}

Tệp 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';
}

Code của bạn được viết trong exercise.gd. main.gd chứa code đầu vào/đầu ra được cung cấp và không thể chỉnh sửa. Giữ mỗi kiểu class_name trong tệp được đặt tên tương ứng.

Tự làm thử

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))

Tất cả bài học trong GDScript dành cho nhà phát triển C++

Tự luyện tập: Trình biên dịch GDScript online