Menu
CoddyTech

Final: migração do inventário

Lição 47 de 48 do curso GDScript para desenvolvedores C da Coddy.

challenge icon

Desafio

Fácil

Implemente a referência em C: receba palavras como entrada e retorne pares palavra=contagem em ordem alfabética, separados por vírgulas, ou none. As palavras estão em ASCII minúsculo, e as duplicatas são contadas separadamente. Não altere a entrada do chamador.

A entrada é um único array JSON na entrada padrão. O main bloqueado faz o parsing, chama as APIs públicas e imprime result= seguido do texto retornado e de uma quebra de linha. Nenhuma função auxiliar deve imprimir. Testes independentes com casos fixos verificam o comportamento exigido da API antes do caso de entrada; eles não impõem um estilo de implementação.

Referência completa em C. Salve estes arquivos juntos e compile main.c com um compilador C17. Os cabeçalhos fornecem a API auxiliar; main lê o mesmo array JSON e imprime o mesmo protocolo de resultado. Nenhuma biblioteca externa é necessária.

Arquivo 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

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

Seu código deve ficar em exercise.gd. main.gd contém o código fornecido de entrada/saída e não pode ser editado. Mantenha cada tipo class_name no arquivo com o nome correspondente.

Experimente você mesmo

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

Todas as lições de GDScript para desenvolvedores C

Pratique por conta própria: Compilador de GDScript online