Menu
CoddyTech

Cの台帳を移植する

Coddyの「C開発者のためのJavaScript」コースのレッスン 47/48。

challenge icon

チャレンジ

簡単

以下のC言語の完全な参照実装を移植してください。入力は[name, quantity]ペアのJSON配列です。名前にはASCII文字のみが含まれ、数量は整数です。名前ごとにすべての更新値を合計し、正の合計値だけを残してください。名前をASCII順に並べ替え、[name, total]ペアを返してください。__proto__のような名前も通常のデータとして扱えるよう、JavaScriptのMapを使用してください。入力の数値と中間の整数合計はすべて、JavaScriptの安全な整数の範囲内に収まります。

C言語の参照実装には、指定されたJSONペア配列の形式に対応する小さなパーサーが含まれており、ASCIIの名前エスケープをデコードして、符号付き64ビットの合計値に累積します。名前の長さは明示的に記録されるため、エスケープされたゼロバイトもデータとして扱われます。キーを並べ替え、文字列をエスケープして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 値を1つ受け取ります。データを返し、solve 内では出力しないでください。
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

C開発者のためのJavaScriptのすべてのレッスン

自分で練習してみよう: JavaScriptオンラインコンパイラ