Menu
CoddyTech

C++のInventoryを移植する

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

challenge icon

チャレンジ

中級

参照用のC++プログラムをLuaモジュールに移植してください。各入力行は、小文字のASCII名、コロン、符号付き整数の差分で構成されます。名前ごとに集計し、最終合計が正のものだけを残し、名前を昇順に並べ、カンマで結合したname=totalのエントリーを返します。残るエントリーがない場合はemptyを返してください。inventory.luaでinventory.aggregate(lines)を実装し、結果の書式設定はappで行います。すべての入力行は正しい形式です。

app.luaとinventory.luaを編集してください。表示されているロック済みのmain.luaは標準入力を一連の行として読み込み、app.run(lines)を呼び出し、返された値を最後に改行を1つ付けて出力します。診断メッセージを出力したり、モジュール名を変更したりしないでください。空の入力は空のシーケンスになります。すべての数値入力はオーバーフローを避けられるほど小さい値です。

公開APIの確認: inventory.aggregate(lines)は、符号付き差分を合計した新しいテーブルを返し、合計がゼロの項目も保持します。空の入力では空のテーブルが返されます。書式設定と絞り込みはappで行います。ロック済みのドライバーはapp.runを呼び出す前にこの動作を確認します。これらの確認は成功時には何も出力しません。

C++17の参照実装

#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';
}

C++のmapは、最初にアクセスしたときにゼロのカウントを挿入し、キーの順序で反復処理します。Luaでは、キーが存在しない場合とゼロが格納されている場合を区別し、符号付き差分を累積してから、出力するキーを明示的にソートしてください。ここでの符号付き整数は、任意の-の後に数字が続く形式です。プラス記号は指定されません。集計と絞り込みを分離し、公開モジュールがゼロと負の合計も返すようにしてください。

自分で試してみよう

-- 公開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++開発者のためのLuaのすべてのレッスン

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