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 الظاهر والمقفل الإدخال القياسي إلى تسلسل من الأسطر، ويستدعي app.run(lines)، ثم يطبع القيمة التي تُعيدها متبوعة بسطر جديد نهائي واحد. لا تطبع رسائل تشخيصية ولا تغيّر أسماء الوحدات. ينتج الإدخال الفارغ تسلسلًا فارغًا. جميع الأعداد المدخلة صغيرة بما يكفي لتجنب تجاوز السعة.

اختبارات الواجهة العامة: تُعيد inventory.aggregate(lines) جدولًا جديدًا يحوي مجاميع الفروق الموقّعة، مع الاحتفاظ بالمجاميع الصفرية. ينتج عن الإدخال الفارغ جدول فارغ. تتم التصفية والتنسيق في app. يتحقق المشغّل المقفل من هذا السلوك قبل استدعاء app.run. لا تطبع هذه الاختبارات أي شيء عند نجاحها.

جرّب بنفسك

-- فحوصات واجهة برمجة التطبيقات العامة
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 عبر الإنترنت