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

Transcrivez la référence C : recevez des mots en entrée et renvoyez des paires mot=nombre triées par ordre alphabétique et séparées par des virgules, ou none. Les mots sont en ASCII minuscule, et 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 programme main verrouillé l’analyse, appelle les API publiques et affiche result= suivi du texte renvoyé et d’un retour à la ligne. Aucune fonction auxiliaire ne doit afficher quoi que ce soit. Des tests indépendants à valeurs fixes vérifient le comportement requis de l’API avant le cas d’entrée ; ils n’imposent pas de style d’implémentation.

Référence C complète. Enregistrez ces fichiers ensemble et compilez main.c avec un compilateur C17. Les en-têtes fournissent l’API auxiliaire ; main lit le même tableau JSON et affiche le même protocole de résultat. Aucune bibliothèque externe n’est nécessaire.

Fichier C inventory.h :

#ifndef INVENTORY_H
#define INVENTORY_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
static int word_compare(const void *a, const void *b) {
    return strcmp(*(const char *const *)a, *(const char *const *)b);
}
/* Returns owned text. The input pointers and strings are never modified. */
static char *inventory_summarize(const char *const *words, size_t n) {
    if (n == 0) {
        char *out = malloc(5);
        if (out) memcpy(out, "none", 5);
        return out;
    }
    if (n > SIZE_MAX / sizeof(char *)) return NULL;
    const char **sorted = malloc(n * sizeof *sorted);
    if (!sorted) return NULL;
    for (size_t i = 0; i < n; ++i) sorted[i] = words[i];
    qsort(sorted, n, sizeof *sorted, word_compare);
    size_t capacity = 1;
    for (size_t i = 0; i < n;) {
        size_t j = i + 1;
        while (j < n && strcmp(sorted[i], sorted[j]) == 0) ++j;
        int length = snprintf(NULL, 0, "%s=%zu", sorted[i], j-i);
        if (length < 0 || (size_t)length + 1 > SIZE_MAX-capacity) {
            free(sorted); return NULL;
        }
        capacity += (size_t)length + 1;
        i = j;
    }
    char *out = malloc(capacity);
    if (!out) { free(sorted); return NULL; }
    size_t used = 0;
    for (size_t i = 0; i < n;) {
        size_t j = i + 1;
        while (j < n && strcmp(sorted[i], sorted[j]) == 0) ++j;
        if (used) out[used++] = ',';
        int written = snprintf(out+used, capacity-used, "%s=%zu", sorted[i], j-i);
        used += (size_t)written;
        i = j;
    }
    free(sorted);
    return out;
}
#endif

Fichier C main.c :

#include <ctype.h>
#include "inventory.h"
static char *read_input(void) {
    size_t used=0, capacity=256;
    char *text=malloc(capacity);
    if (!text) return NULL;
    int ch;
    while ((ch=getchar()) != EOF) {
        if (used+1 == capacity) {
            if (capacity > SIZE_MAX/2) { free(text); return NULL; }
            capacity *= 2;
            char *next=realloc(text,capacity);
            if (!next) { free(text); return NULL; }
            text=next;
        }
        text[used++]=(char)ch;
    }
    text[used]=0;
    return text;
}
static void space(const char **p) {
    while (**p==' ' || **p=='\t' || **p=='\r' || **p=='\n') ++*p;
}
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;
    return -1;
}
/* The input contract is a JSON array of lowercase ASCII words. */
static char *word(const char **p) {
    if (*(*p)++ != '"') return NULL;
    char *out=malloc(strlen(*p)+1);
    if (!out) return NULL;
    size_t n=0;
    while (**p && **p!='"') {
        unsigned value=(unsigned char)*(*p)++;
        if (value=='\\') {
            if (*(*p)++ != 'u') { free(out); return NULL; }
            value=0;
            for (int k=0;k<4;++k) {
                int h=hex(**p);
                if (h<0) { free(out); return NULL; }
                ++*p; value=value*16+(unsigned)h;
            }
        }
        if (value<'a' || value>'z') { free(out); return NULL; }
        out[n++]=(char)value;
    }
    if (**p!='"') { free(out); return NULL; }
    ++*p; out[n]=0;
    return out;
}
int main(void) {
    char *text=read_input();
    if (!text) return 1;
    const char *p=text;
    char **words=NULL; size_t count=0; int status=1;
    space(&p);
    if (*p++ != '[') goto done;
    space(&p);
    while (*p != ']') {
        char *next=word(&p);
        if (!next) goto done;
        char **grown=realloc(words,(count+1)*sizeof *words);
        if (!grown) { free(next); goto done; }
        words=grown; words[count++]=next;
        space(&p);
        if (*p==']') break;
        if (*p++ != ',') goto done;
        space(&p);
    }
    ++p; space(&p);
    if (*p) goto done;
    char *summary=inventory_summarize((const char *const *)words,count);
    if (!summary) goto done;
    printf("result=%s\n",summary);
    free(summary); status=0;
done:
    for (size_t i=0;i<count;++i) free(words[i]);
    free(words); free(text);
    return status;
}

Votre code va dans exercise.gd. main.gd contient le code fourni pour l’entrée et la sortie et ne peut pas être modifié. Placez chaque type class_name dans le fichier portant son nom.

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