Menu
CoddyTech

C 인벤토리 포팅하기

Coddy의 C 개발자를 위한 Lua 코스 레슨. 48개 중 47번째.

challenge icon

챌린지

중급

C 버전은 항목으로 이루어진 동적 배열과 각 항목마다 할당된 이름 하나를 소유합니다. 결과를 출력한 뒤 해당 메모리를 해제합니다. Lua 테이블은 이러한 메모리 관리를 대신하므로, 집계 및 정렬 동작을 그대로 유지하세요.

참조 C 프로그램을 Lua 모듈로 옮기세요. 각 입력 줄은 소문자 ASCII 이름, 콜론, 부호가 있는 정수 증분으로 이루어집니다. 이름별로 값을 집계하고, 최종 합계가 양수인 항목만 남긴 다음, 이름을 오름차순으로 정렬하고 name=total 항목을 쉼표로 연결해 반환하세요. 남은 항목이 없으면 empty를 반환하세요. inventory.lua에서 inventory.aggregate(lines)를 구현하고, app에서 결과를 형식화하세요. 모든 입력 줄은 올바른 형식입니다.

C 참조 코드

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <errno.h>

struct Entry { char *name; long total; };

/* The caller owns each returned line, including a final line without newline. */
static int read_line(char **out) {
    size_t length = 0, capacity = 32;
    char *line = malloc(capacity);
    int ch;
    if (line == NULL) return -1;
    while ((ch = getchar()) != EOF && ch != '\n') {
        if (length == capacity - 1) {
            if (capacity > SIZE_MAX / 2) { free(line); return -1; }
            capacity *= 2;
            char *grown = realloc(line, capacity);
            if (grown == NULL) { free(line); return -1; }
            line = grown;
        }
        line[length++] = (char)ch;
    }
    if (ferror(stdin)) { free(line); return -1; }
    if (ch == EOF && length == 0) { free(line); return 0; }
    line[length] = '\0';
    *out = line;
    return 1;
}

static int by_name(const void *left, const void *right) {
    const struct Entry *a = left, *b = right;
    return strcmp(a->name, b->name);
}

int main(void) {
    struct Entry *entries = NULL;
    size_t count = 0;
    int status = 0, result;
    char *line = NULL;
    while ((result = read_line(&line)) == 1) {
        char *separator = strchr(line, ':');
        if (separator == NULL || separator == line) { status = 1; break; }
        *separator = '\0';
        for (const char *p = line; *p != '\0'; ++p)
            if (*p < 'a' || *p > 'z') status = 1;
        const char *digits = separator + 1;
        if (*digits == '-') ++digits;
        if (*digits == '\0') status = 1;
        for (const char *p = digits; *p != '\0'; ++p)
            if (*p < '0' || *p > '9') status = 1;
        errno = 0;
        char *end;
        long delta = strtol(separator + 1, &end, 10);
        if (status || errno == ERANGE || *end != '\0') { status = 1; break; }
        size_t index = 0;
        while (index < count && strcmp(entries[index].name, line) != 0) ++index;
        if (index == count) {
            if (count == SIZE_MAX / sizeof *entries) { status = 1; break; }
            struct Entry *grown = realloc(entries, (count + 1) * sizeof *entries);
            if (grown == NULL) { status = 1; break; }
            entries = grown;
            entries[count++] = (struct Entry){line, 0};
            line = NULL; /* Transfer ownership to the new entry. */
        }
        long old = entries[index].total;
        if ((delta > 0 && old > LONG_MAX - delta) ||
            (delta < 0 && old < LONG_MIN - delta)) { status = 1; break; }
        entries[index].total += delta;
        free(line);
        line = NULL;
    }
    if (result < 0) status = 1;
    free(line);
    if (!status) {
        if (count > 1) qsort(entries, count, sizeof *entries, by_name);
        int printed = 0;
        for (size_t i = 0; i < count; ++i) {
            if (entries[i].total > 0) {
                printf("%s%s=%ld", printed ? "," : "", entries[i].name, entries[i].total);
                printed = 1;
            }
        }
        if (!printed) fputs("empty", stdout);
        putchar('\n');
    }
    for (size_t i = 0; i < count; ++i) free(entries[i].name);
    free(entries);
    return status || ferror(stdout);
}

app.lua, inventory.lua를 수정하세요. 화면에 보이는 잠금된 main.lua는 stdin을 읽어 줄 목록을 만들고, app.run(lines)을 호출한 다음 반환된 값을 마지막에 줄바꿈 하나와 함께 출력합니다. 진단 메시지를 출력하거나 모듈 이름을 변경하지 마세요. 입력이 비어 있으면 빈 목록이 됩니다. 모든 숫자 입력은 오버플로가 발생하지 않을 만큼 작습니다.

공개 API 검사: inventory.aggregate(lines)는 부호가 있는 증분의 합계를 담은 새 테이블을 반환하며, 합계가 0인 항목도 유지합니다. 입력이 비어 있으면 빈 테이블을 반환합니다. 형식화와 필터링은 app에서 수행합니다. 잠금된 드라이버는 app.run을 호출하기 전에 이 동작을 검사합니다. 검사가 성공하면 아무것도 출력하지 않습니다.

직접 해보기

-- 공개 API 검사
do
local inventory=require("inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))

C 개발자를 위한 Lua의 모든 레슨

직접 연습해 보세요: 온라인 Lua 컴파일러