인벤토리 이식하기
Coddy의 C# 개발자를 위한 Luau 코스 레슨. 48개 중 47번째.
챌린지
중급참조 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는 stdin을 읽어 줄 목록으로 만든 다음, app.run(lines)을 호출하고 반환값을 마지막에 줄바꿈 하나를 넣어 출력합니다. 진단 메시지를 출력하거나 모듈 이름을 변경하지 마세요. 입력이 비어 있으면 빈 목록이 됩니다. 모든 숫자 입력은 오버플로가 발생하지 않을 만큼 작습니다.
공개 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 컴파일러