C#のインベントリを移植する
Coddyの「C#開発者のためのLua」コースのレッスン 47/48。
チャレンジ
中級参照用のC#プログラムをLuaモジュールに移植してください。各入力行は、小文字のASCII名、コロン、符号付き整数の差分で構成されます。名前ごとに集計し、最終合計が正のものだけを残して、名前を昇順に並べ、name=totalのエントリーをカンマで結合して返します。残るものがなければemptyを返します。inventory.luaにinventory.aggregate(lines)を実装してください。結果の書式設定はappで行います。すべての入力行は正しい形式です。
C#の参照実装
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
var totals=new SortedDictionary<string,long>(StringComparer.Ordinal);
string line;
while((line=Console.ReadLine())!=null){
int colon=line.IndexOf(':');
string name=line.Substring(0,colon);
long delta=long.Parse(line.Substring(colon+1),System.Globalization.CultureInfo.InvariantCulture);
totals.TryGetValue(name,out long old);
totals[name]=old+delta;
}
var rows=totals.Where(x=>x.Value>0).Select(x=>x.Key+"="+x.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToArray();
Console.WriteLine(rows.Length>0 ? string.Join(",",rows) : "empty");
app.luaとinventory.luaを編集してください。表示されているロック済みのmain.luaは、標準入力を一連の行として読み込み、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#開発者のためのLuaのすべてのレッスン
自分で練習してみよう: Luaオンラインコンパイラ