Menu
CoddyTech

הסבת מערכת המלאי

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

challenge icon

אתגר

בינוני

העבירו את תוכנית הייחוס ב-C++ למודולים של Luau. כל שורת קלט היא שם באותיות ASCII קטנות, נקודתיים והפרש שלם עם סימן. חשבו את הסכום לכל שם, השאירו רק סכומים סופיים חיוביים, מיינו את השמות בסדר עולה והחזירו רשומות name=total מופרדות בפסיקים. החזירו empty אם לא נותרו רשומות. ממשו את inventory.aggregate(lines) בקובץ inventory.luau; app אחראי לעיצוב התוצאה. כל שורות הקלט תקינות.

תוכנית ייחוס ב-C++

#include <iostream>
#include <map>
#include <string>
// Input: lowercase ASCII name, colon, decimal delta with optional minus sign.
// Values and totals are small enough to be represented exactly in Lua 5.1.
std::map<std::string, long long> aggregate(std::istream& input) {
    std::map<std::string, long long> counts;
    std::string line;
    while (std::getline(input, line)) {
        const auto colon = line.find(':');
        counts[line.substr(0, colon)] += std::stoll(line.substr(colon + 1));
    }
    return counts;
}
int main() {
    const auto counts = aggregate(std::cin);
    bool first = true;
    for (const auto& entry : counts) {
        if (entry.second <= 0) continue;
        if (!first) std::cout << ',';
        std::cout << entry.first << '=' << entry.second;
        first = false;
    }
    if (first) std::cout << "empty";
    std::cout << '\n';
}

ערכו את app.luau, inventory.luau. הקובץ הגלוי והנעול main.luau קורא את stdin לרצף של שורות, קורא ל-app.run(lines) ומדפיס את הערך שהפונקציה מחזירה, עם תו newline אחד בסוף. אל תדפיסו הודעות אבחון ואל תשנו את שמות המודולים. קלט ריק יוצר רצף ריק. כל הערכים המספריים קטנים מספיק כדי למנוע גלישה.

בדיקות API ציבורי: inventory.aggregate(lines) מחזירה טבלה חדשה של סכומי ההפרשים החתומים, ומשמרת סכומים שערכם אפס. קלט ריק מחזיר טבלה ריקה. העיצוב והסינון מתבצעים ב-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))

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

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