최종: 주식 장부
Coddy의 Java 개발자를 위한 R 코스 레슨. 48개 중 47번째.
챌린지
쉬움summarize(rows)를 구현하세요. 각 행은 소문자 ASCII 항목 이름과 부호가 있는 정수 금액이 공백 하나로 구분된 형태입니다. 이름별로 금액을 합산하고, 양수인 합계만 유지하며, 이름을 사전순으로 정렬하세요. 이름:합계 항목을 줄바꿈으로 구분해 반환하고, 항목이 없으면 empty를 반환하세요. 입력이 비어 있어도 유효합니다.
선언된 공개 API를 유지하세요. 화면에 표시되는 잠금된 드라이버는 이를 직접 확인하고 solve(lines)도 출력합니다. 입력은 명시된 계약을 따르며, 모든 연산은 작고 유한한 값으로 이루어집니다.
코드는 Functions.R와 Exercise.R에 작성하세요. main.R은 종속 항목을 순서대로 불러오고 제공된 입력/출력 코드를 포함합니다. 이 파일은 수정할 수 없습니다.
이 완전한 Java 참조 구현을 R 공개 API로 포팅하세요. 이 구현은 동일한 유효 입력 계약을 따릅니다.
import java.io.*;
import java.util.*;
public class Main {
static String summarize(List<String> rows) {
Map<String,Long> totals = new TreeMap<>();
for (String row : rows) {
int space = row.indexOf(' ');
String name = row.substring(0,space);
long amount = Long.parseLong(row.substring(space+1));
totals.put(name, Math.addExact(totals.getOrDefault(name,0L),amount));
}
List<String> lines = new ArrayList<>();
for (var entry : totals.entrySet()) {
if (entry.getValue()>0) lines.add(entry.getKey()+":"+entry.getValue());
}
return lines.isEmpty() ? "empty" : String.join("\n",lines);
}
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
List<String> rows = new ArrayList<>();
String line;
while ((line=input.readLine())!=null) rows.add(line);
System.out.println(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="")
Java 개발자를 위한 R의 모든 레슨
직접 연습해 보세요: 온라인 R 컴파일러