최종: 주식 장부
Coddy의 C# 개발자를 위한 R 코스 레슨. 48개 중 47번째.
챌린지
쉬움summarize(rows)를 구현하세요. 각 행은 소문자 ASCII 항목 이름과 부호가 있는 정수 수량이 공백 하나로 구분된 형식입니다. 이름별로 수량을 합산하고, 양수인 합계만 남긴 다음, 이름을 사전순으로 정렬하세요. 이름:합계 항목을 줄바꿈으로 구분해 반환하고, 항목이 없으면 empty를 반환하세요. 입력이 비어 있어도 유효합니다.
선언된 공개 API를 유지하세요. 화면에 표시되는 잠금된 드라이버는 공개 API를 직접 확인하고 solve(lines)도 출력합니다. 입력은 명시된 계약을 따르며, 모든 산술 연산의 값은 작고 유한합니다.
코드는 Functions.R와 Exercise.R에 작성하세요. main.R은 종속 항목을 순서대로 불러오고 제공된 입력/출력 코드를 포함합니다. 이 파일은 수정할 수 없습니다.
이 완전한 C# 참조 구현을 R 공개 API로 옮기세요. 이 구현은 동일한 유효 입력 계약을 따릅니다.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
static string Summarize(IEnumerable<string> rows) {
var totals = new SortedDictionary<string,long>(StringComparer.Ordinal);
foreach (string row in rows) {
int space = row.IndexOf(' ');
string name = row[..space];
long amount = long.Parse(row[(space+1)..], CultureInfo.InvariantCulture);
totals.TryGetValue(name, out long current);
totals[name] = checked(current + amount);
}
var lines = totals.Where(pair => pair.Value > 0)
.Select(pair => pair.Key + ":" + pair.Value.ToString(CultureInfo.InvariantCulture))
.ToArray();
return lines.Length == 0 ? "empty" : string.Join("\n", lines);
}
var rows = new List<string>();
string line;
while ((line = Console.ReadLine()) != null) rows.Add(line);
Console.WriteLine(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="")
C# 개발자를 위한 R의 모든 레슨
직접 연습해 보세요: 온라인 R 컴파일러