Menu
CoddyTech

הסבה: פקודות מלאי

שיעור 47 מתוך 48 בקורס Swift למפתחי C של Coddy.

challenge icon

אתגר

בינוני

העבירו את מימוש הייחוס ב־C ל־Swift. ממשו את Inventory() עם add(_ name: String, count: Int) -> Bool, take(_ name: String, count: Int) -> Bool, quantity(of name: String) -> Int ו־report() -> String. הפונקציה Add מקבלת רק כמויות חיוביות. הפונקציה Take מקבלת רק כמויות חיוביות שאינן עולות על המלאי הנוכחי. דחיות משמרות את כל המצב; הכמויות של פריטים לא מוכרים הן אפס. פעולות Take מוצלחות משאירות רשומות עם מלאי אפס. הציגו בדוח את כל השמות השמורים בסדר עולה, בפורמט name:quantity, מופרדים ברווחים. הקלט מכיל 0 עד 40 שלשות פקודות: add name count או take name count. השמות הם מילים באותיות ASCII קטנות, באורך של עד 10 אותיות, והכמויות הן בטווח -10 עד 100. הפלט הוא מספר הפקודות שהצליחו, ואחריו רווח ודוח רק אם הוא אינו ריק.

ממשו את ממשקי ה־API הנדרשים ואת solve(_ input: String) -> String. החזירו את טקסט הפלט ללא ירידת שורה בסוף; אל תדפיסו בקוד שניתן לעריכה. מנהל ההתקן הנעול בודק באופן עצמאי את ממשקי ה־API על קלטים תקינים נוספים, ואז מדפיס את הטקסט שהוחזר עם ירידת שורה אחת בדיוק. כל הפעולות המספריות נשארות בגבולות של Int.

מימוש Inventory ב־C מאחסן רשומות מוגבלות בתוך המבנה ומעדכן את המקור באמצעות מצביע. הוא ממיין מערך זמני עבור הדוח, בלי לשנות את המצב השמור. שמרו על ממשק ה־API הנדרש של Swift עם טיפוס ייחוס, ועל כל המצב לאחר פקודות שנדחו.

תוכנית הייחוס המלאה ב־C. קומפלו את main.c כשהקובץ inventory.h נמצא לצדו; הכותרת מספקת את המימוש שבו משתמשת נקודת הכניסה היחידה. המימוש הושלם בכוונה עבור ההעברה הסופית הזו.

inventory.h

#ifndef INVENTORY_H
#define INVENTORY_H
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { char name[11]; int quantity; } Item;
typedef struct { Item items[40]; int size; } Inventory;
static int inventory_find(const Inventory *inventory, const char *name) {
    for (int i = 0; i < inventory->size; ++i)
        if (strcmp(inventory->items[i].name, name) == 0) return i;
    return -1;
}
static int inventory_quantity(const Inventory *inventory, const char *name) {
    int index = inventory_find(inventory, name);
    return index < 0 ? 0 : inventory->items[index].quantity;
}
static bool inventory_add(Inventory *inventory, const char *name, int count) {
    if (count <= 0) return false;
    int index = inventory_find(inventory, name);
    if (index < 0) {
        index = inventory->size++;
        strcpy(inventory->items[index].name, name);
        inventory->items[index].quantity = 0;
    }
    inventory->items[index].quantity += count;
    return true;
}
static bool inventory_take(Inventory *inventory, const char *name, int count) {
    int available = inventory_quantity(inventory, name);
    if (count <= 0 || count > available) return false;
    inventory->items[inventory_find(inventory, name)].quantity = available - count;
    return true;
}
static int item_compare(const void *left, const void *right) {
    return strcmp(((const Item *)left)->name, ((const Item *)right)->name);
}
static void inventory_report(const Inventory *inventory, char output[1024]) {
    Item sorted[40];
    memcpy(sorted, inventory->items, (size_t)inventory->size * sizeof(Item));
    qsort(sorted, (size_t)inventory->size, sizeof(Item), item_compare);
    size_t used = 0;
    output[0] = '\0';
    for (int i = 0; i < inventory->size; ++i)
        used += (size_t)snprintf(output + used, 1024 - used, "%s%s:%d", i ? " " : "", sorted[i].name, sorted[i].quantity);
}
#endif

main.c

#include "inventory.h"
int main(void) {
    Inventory inventory = {0};
    char command[5], name[11], report[1024];
    int count, accepted = 0;
    while (scanf("%4s %10s %d", command, name, &count) == 3) {
        bool ok = strcmp(command, "add") == 0
            ? inventory_add(&inventory, name, count)
            : inventory_take(&inventory, name, count);
        if (ok) ++accepted;
    }
    inventory_report(&inventory, report);
    printf("%d%s%s\n", accepted, report[0] ? " " : "", report);
    return 0;
}

ממשו את ממשקי ה־API של Swift בקבצים Inventory.swift, Functions.swift. השאירו את מנהל ההתקן שסופק בקובץ main.swift.

נסו בעצמכם

import Foundation
func apiChecks(_ input: String) -> Bool {
let x = Inventory(); guard x.quantity(of: "missing") == 0 && !x.take("missing", count: 1) && x.report().isEmpty else { return false }; guard x.add("oak", count: 4) && !x.take("oak", count: 5) && !x.add("oak", count: 0) && x.quantity(of: "oak") == 4 else { return false }; return x.take("oak", count: 4) && x.report() == "oak:0" && !x.take("oak", count: -1) && Inventory().report().isEmpty
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// תחילת בדיקות API ציבורי
let apiOK = apiChecks(input)
// סיום בדיקות API ציבורי
if apiOK { print(solve(input)) } else { print("API mismatch") }

כל השיעורים ביחידה Swift למפתחי C

תרגלו בעצמכם: Swift אונליין