העבר פנקס חשבונות ב-C
שיעור 47 מתוך 48 בקורס JavaScript למפתחי C של Coddy.
אתגר
קלהסבו את מימוש הייחוס המלא ב־C שלהלן. הקלט הוא מערך JSON אחד של זוגות [name, quantity]. השמות מכילים תווי ASCII בלבד, והכמויות הן מספרים שלמים. סכמו כל עדכון לפי שם, ואז השאירו רק סכומים חיוביים. מיינו את השמות לפי סדר ASCII והחזירו זוגות [name, total]. השתמשו ב־Map של JavaScript, כדי ששמות כמו __proto__ יישארו נתונים רגילים. כל מספרי הקלט וסכומי הביניים השלמים נמצאים בטווח המספרים השלמים הבטוח של JavaScript.
מימוש הייחוס ב־C כולל מנתח קטן עבור חוזה מערך זוגות ה־JSON המתואר, מפענח רצפי בריחה של שמות ASCII וצובר סכומים שלמים בני 64 סיביות עם סימן. אורכי השמות מתועדים במפורש, כך שגם בית אפס שעבר בריחה נשאר נתון. המימוש ממיין את המפתחות ומפיק JSON עם תווי בריחה למחרוזות. Map של JavaScript מספק את ההתנהגות של מפתחות נתונים, בעוד ש־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 והשאירו את ממשק ה־API המיוצא solve(input). מנהל ההתקן הנעול הגלוי driver.js קורא JSON ומדפיס את ערך ההחזרה כ־JSON קומפקטי ואחריו שורה חדשה. אל תוסיפו פלט אבחון.
נסו בעצמכם
import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// ערך JSON אחד מתקבל דרך stdin. החזירו נתונים; אל תדפיסו בתוך solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));
כל השיעורים ביחידה JavaScript למפתחי C
1היכרות ראשונה עם JavaScript
הרצת JavaScriptעיצוב תבניותהצהרות ושינוי שיוךטיפוסי מספרים שלמים ו-NumberNull ו-Undefinedסיכום: קבלה4צינורות איטרציה
While ויציאה מוקדמתלולאות ופונקציות callback של מערכיםערכי התחלה וצמצומיםמיון וסימני השוואהסיכום: בניית דירוג2החלטות וזרימת תוכנית
ערכים וזהותבדיקות סקלריות וערכי אמתIf וערכים מותניםלולאות עם אינדקס ו-For-ofסיכום: כללי שילוחתרגלו בעצמכם: קומפיילר JavaScript אונליין