Menu
CoddyTech

インベントリを移植する

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

challenge icon

チャレンジ

中級

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

Swiftの参照実装

var counts: [String: Int] = [:]
while let line = readLine() {
    let pieces = line.split(separator: ":", maxSplits: 1)
    let name = String(pieces[0])
    counts[name, default: 0] += Int(pieces[1])!
}
let rows = counts.keys.sorted().filter { counts[$0]! > 0 }
    .map { "\($0)=\(counts[$0]!)" }
print(rows.isEmpty ? "empty" : rows.joined(separator: ","))

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

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

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