Menu
CoddyTech

C 장부 이식하기

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

challenge icon

챌린지

쉬움

아래의 완전한 C 참조 구현을 포팅하세요. 입력은 [name, quantity] 쌍으로 이루어진 JSON 배열 하나입니다. 이름에는 ASCII 문자만 포함되며 수량은 정수입니다. 이름별로 모든 업데이트를 합산한 다음, 양수인 합계만 남기세요. 이름을 ASCII 순서로 정렬하고 [name, total] 쌍을 반환하세요. __proto__와 같은 이름도 일반 데이터로 유지되도록 JavaScript Map을 사용하세요. 모든 입력 숫자와 중간 정수 합계는 JavaScript의 안전한 정수 범위 안에 있습니다.

C 참조 구현에는 명시된 JSON 쌍 배열 계약을 위한 작은 파서가 포함되어 있고, ASCII 이름 이스케이프를 디코딩하며 부호 있는 64비트 합계에 누적합니다. 이름 길이를 명시적으로 추적하므로 이스케이프된 0바이트도 데이터로 유지됩니다. 키를 정렬하고 문자열 이스케이프를 적용해 JSON을 출력합니다. JavaScript Map은 데이터 키 동작을 제공하며, Number는 명시된 안전한 정수 범위 내에서 정확합니다. 마지막 정렬도 명시적으로 수행하세요. 잠긴 JavaScript 드라이버가 JSON 디코딩과 인코딩을 담당합니다.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdint.h>
#include <inttypes.h>

/* Valid input is a JSON array of [ASCII name, integer quantity] pairs.
   All quantities and intermediate totals are within the safe integer bound. */
typedef struct { unsigned char *bytes; size_t length; int64_t total; } Entry;
static const char *cursor;
static void require(int ok) { if (!ok) exit(EXIT_FAILURE); }
static void *resize(void *old, size_t size) {
    void *next = realloc(old, size);
    require(next != NULL);
    return next;
}
static void whitespace(void) {
    while (*cursor && isspace((unsigned char)*cursor)) cursor++;
}
static void token(char expected) {
    whitespace();
    require(*cursor == expected);
    cursor++;
}
static unsigned hex(char c) {
    if (c >= '0' && c <= '9') return (unsigned)(c-'0');
    if (c >= 'a' && c <= 'f') return (unsigned)(c-'a'+10);
    if (c >= 'A' && c <= 'F') return (unsigned)(c-'A'+10);
    require(0); return 0;
}
static Entry name_string(void) {
    token('"');
    Entry name = {resize(NULL, strlen(cursor)+1), 0, 0};
    while (*cursor != '"') {
        require(*cursor != '\0');
        unsigned value = (unsigned char)*cursor++;
        if (value == '\\') {
            require(*cursor != '\0');
            char escape = *cursor++;
            switch (escape) {
                case '"': value='"'; break;
                case '\\': value='\\'; break;
                case '/': value='/'; break;
                case 'b': value='\b'; break;
                case 'f': value='\f'; break;
                case 'n': value='\n'; break;
                case 'r': value='\r'; break;
                case 't': value='\t'; break;
                case 'u':
                    value=0;
                    for (int i=0;i<4;i++) {
                        require(*cursor != '\0');
                        value=value*16+hex(*cursor++);
                    }
                    break;
                default: require(0);
            }
        }
        require(value <= 127);
        name.bytes[name.length++]=(unsigned char)value;
    }
    cursor++;
    return name;
}
static int compare_names(const void *left, const void *right) {
    const Entry *a=left,*b=right;
    size_t common=a->length<b->length ? a->length:b->length;
    int order=memcmp(a->bytes,b->bytes,common);
    return order ? order : (a->length>b->length)-(a->length<b->length);
}
static void print_name(const Entry *entry) {
    putchar('"');
    for(size_t i=0;i<entry->length;i++) {
        unsigned c=entry->bytes[i];
        switch(c) {
            case '"': fputs("\\\"",stdout); break;
            case '\\': fputs("\\\\",stdout); break;
            case '\b': fputs("\\b",stdout); break;
            case '\f': fputs("\\f",stdout); break;
            case '\n': fputs("\\n",stdout); break;
            case '\r': fputs("\\r",stdout); break;
            case '\t': fputs("\\t",stdout); break;
            default:
                if(c<32) printf("\\u%04x",c);
                else putchar((int)c);
        }
    }
    putchar('"');
}
int main(void) {
    size_t used=0,capacity=256;
    char *input=resize(NULL,capacity);
    int ch;
    while((ch=getchar())!=EOF) {
        if(used+1==capacity) input=resize(input,capacity*=2);
        input[used++]=(char)ch;
    }
    input[used]='\0';
    cursor=input;
    size_t count=0,slots=8;
    Entry *entries=resize(NULL,slots*sizeof *entries);
    token('['); whitespace();
    if(*cursor!=']') {
        for(;;) {
            token('[');
            Entry name=name_string();
            token(','); whitespace();
            char *end;
            double value=strtod(cursor,&end);
            require(end!=cursor && value>=-9007199254740991.0 && value<=9007199254740991.0);
            cursor=end;
            int64_t quantity=(int64_t)value;
            require((double)quantity==value);
            token(']');
            size_t index=0;
            while(index<count && compare_names(&entries[index],&name)!=0) index++;
            if(index==count) {
                if(count==slots) entries=resize(entries,(slots*=2)*sizeof *entries);
                entries[count++]=name;
            } else free(name.bytes);
            entries[index].total+=quantity;
            whitespace();
            if(*cursor!=',') break;
            cursor++;
        }
    }
    token(']'); whitespace(); require(*cursor=='\0');
    qsort(entries,count,sizeof *entries,compare_names);
    putchar('[');
    int first=1;
    for(size_t i=0;i<count;i++) {
        if(entries[i].total>0) {
            if(!first) putchar(',');
            first=0;
            putchar('[');print_name(&entries[i]);
            printf(",%" PRId64 "]",entries[i].total);
        }
        free(entries[i].bytes);
    }
    puts("]");
    free(entries);free(input);
    return 0;
}

exercise.js를 수정하고 내보내는 solve(input) API는 그대로 유지하세요. 화면에 표시된 잠긴 driver.js는 JSON을 읽고 반환값을 공백 없는 JSON으로 출력한 뒤 줄바꿈을 덧붙입니다. 진단용 출력을 추가하지 마세요.

직접 해보기

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// stdin으로 JSON 값 하나가 입력됩니다. 데이터를 반환하고 solve 안에서는 출력하지 마세요.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

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

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