Final: Inventory Port
Lesson 47 of 48 in Coddy's GDScript for C Developers course.
Challenge
EasyPort the C reference: input words, return alphabetically sorted word=count pairs joined by commas, or none. Words are lowercase ASCII, duplicates count separately. Do not change caller input.
Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.
Complete C reference. Save these files together and compile main.c with a C17 compiler. The headers provide the helper API; main reads the same JSON array and prints the same result protocol. No external library is required.
C file 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
C file 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;
}
Your code goes in exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.
Try it yourself
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))
All lessons in GDScript for C Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command CountPractice on your own: Online GDScript compiler