최종: 재고 장부
Coddy의 Luau 개발자를 위한 R 코스 레슨. 48개 중 47번째.
챌린지
쉬움summarize(rows)를 구현하세요. 각 행은 소문자 ASCII 항목 이름과 부호가 있는 정수가 공백 하나로 구분된 형태입니다. 이름별로 수량을 합산하고, 양수인 합계만 남긴 다음, 이름을 사전순으로 정렬하세요. 이름:합계 항목을 줄바꿈으로 구분해 반환하고, 항목이 없으면 빈 문자열을 반환하세요. 입력이 비어 있어도 유효합니다.
선언된 공개 API를 유지하세요. 화면에 표시되는 잠금된 드라이버는 solve(lines)를 출력할 뿐만 아니라 API를 직접 검사합니다. 입력은 명시된 계약을 따르며, 모든 연산 값은 작고 유한합니다.
코드는 Functions.R와 Exercise.R에 작성하세요. main.R은 종속 항목을 순서대로 불러오고 제공된 입출력 코드를 포함하므로 수정할 수 없습니다.
이 완전한 Luau 참조 구현을 R 공개 API로 포팅하세요. 이 코드는 동일한 유효 입력 계약을 구현합니다.
local function summarize(rows)
local totals = {}
for _, row in ipairs(rows) do
local space = assert(row:find(" ", 1, true))
local name = row:sub(1, space - 1)
local amount = assert(tonumber(row:sub(space + 1)))
totals[name] = (totals[name] or 0) + amount
end
local names = {}
for name, total in pairs(totals) do
if total > 0 then names[#names + 1] = name end
end
table.sort(names)
local lines = {}
for _, name in ipairs(names) do
lines[#lines + 1] = name .. ":" .. string.format("%.0f", totals[name])
end
return #lines == 0 and "empty" or table.concat(lines, "\n")
end
local rows = {}
for line in io.lines() do rows[#rows + 1] = line end
print(summarize(rows))
직접 해보기
source("Functions.R")
source("Exercise.R")
stopifnot(identical(summarize(c("q 9","q -2","b 1")),"b:1\nq:7"))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
Luau 개발자를 위한 R의 모든 레슨
직접 연습해 보세요: 온라인 R 컴파일러