Menu
CoddyTech

Final : Port d'inventaire

Leçon 47 sur 48 du cours GDScript pour les développeurs C++ de Coddy.

challenge icon

Défi

Facile

Portez la référence C++ : recevez des mots en entrée, retournez des paires mot=nombre triées par ordre alphabétique séparées par des virgules, ou "none". Les mots sont en ASCII minuscules, les doublons sont comptés séparément. Ne modifiez pas l'entrée de l'appelant.

L'entrée est un tableau JSON sur stdin. Le main verrouillé l'analyse, appelle les API publiques et affiche result= suivi du texte retourné et d'un saut de ligne. Aucun helper ne doit effectuer d'impression. Des sondes fixes indépendantes vérifient le comportement requis de l'API avant le cas d'entrée ; elles n'imposent aucun style d'implémentation.

Référence C++ complète. Enregistrez ces fichiers ensemble et compilez main.cpp avec C++20. Les en-têtes fournissent les API d'assistance ; main lit le même tableau JSON et affiche le même protocole de résultat. Seule la bibliothèque standard est utilisée.

Fichier 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;
}

Fichier 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';
}

Votre code va dans exercise.gd. main.gd contient le code d'entrée/sortie fourni et ne peut pas être modifié. Conservez chaque type class_name dans son fichier nommé.

Essayez vous-même

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

Toutes les leçons de GDScript pour les développeurs C++

Entraînez-vous par vous-même : Compilateur GDScript en ligne