Menu
CoddyTech

インベントリを移植する

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

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)を呼び出し、返された値を最後に改行を1つ付けて出力します。診断メッセージを出力したり、モジュール名を変更したりしないでください。入力が空の場合は、空のシーケンスになります。すべての数値入力は、オーバーフローしない範囲です。

公開APIの確認: inventory.aggregate(lines)は、符号付き差分を合計した新しいテーブルを返し、合計が0の項目も保持します。入力が空の場合は、空のテーブルを返します。結果の形式設定とフィルタリングは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))

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

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