Menu
CoddyTech

インベントリを移植する

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

challenge icon

チャレンジ

中級

参照用のC#プログラムをLuauモジュールに移植してください。各入力行は、小文字のASCII名、コロン、符号付き整数の差分で構成されます。名前ごとに集計し、最終合計が正のものだけを残し、名前を昇順に並べて、name=totalの項目をカンマで結合して返します。残る項目がない場合はemptyを返します。inventory.luauに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.luauとinventory.luauを編集してください。表示されているロック済みのmain.luauは、標準入力を一連の行として読み込み、app.run(lines)を呼び出し、返された値を最後に改行を1つ付けて出力します。診断メッセージを出力したり、モジュール名を変更したりしないでください。入力が空の場合は空の一連の行になります。数値入力はすべてオーバーフローを避けられる範囲です。

公開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))

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

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