R 장부 포팅하기
Coddy의 R 개발자를 위한 JavaScript 코스 레슨. 48개 중 47번째.
챌린지
쉬움함께 제공된 R 참조 프로그램을 JavaScript로 옮기세요. 입력은 [name,quantity] 쌍으로 이루어진 배열입니다. 이름은 문자열이고 수량은 정수입니다. 이름별로 수량을 합산하고, 양수인 합계만 유지한 뒤, ASCII 순서로 이름을 정렬하고 [name,total] 쌍을 반환하세요. 프로토타입과 비슷한 이름도 작동하도록 Map을 사용하세요. 이름에는 ASCII 문자만 포함됩니다.
R 참조 프로그램입니다. 계약에 맞춘 JSON 어댑터는 ASCII 이름을 바이트 값으로 유지하며, 삽입된 NUL도 그대로 보존하고, 안전한 조회와 ASCII 정렬을 위해 16진수 환경 키를 사용합니다. Double 값은 문서화된 안전한 정수 합계를 보존합니다. JSON 값 하나를 읽고 JSON을 출력합니다.
# Narrow JSON adapter for well-formed arrays of [ASCII name, integer] pairs.
# Names stay as byte values, so embedded NUL does not become an R string.
text <- paste(readLines(file("stdin"),warn=FALSE),collapse="\n")
input <- utf8ToInt(text)
position <- 1L
peek <- function() if(position<=length(input)) input[position] else -1L
space <- function() {
while(peek() %in% c(9L,10L,13L,32L)) position <<- position+1L
}
take <- function(value) {
space()
stopifnot(peek()==value)
position <<- position+1L
}
read_name <- function() {
take(34L)
bytes <- integer()
repeat {
byte <- peek()
stopifnot(byte>=0L)
position <<- position+1L
if(byte==34L) break
if(byte==92L) {
kind <- peek()
position <<- position+1L
if(kind==117L) {
digits <- intToUtf8(input[position:(position+3L)])
byte <- strtoi(digits,base=16L)
stopifnot(!is.na(byte),byte<=127L)
position <<- position+4L
} else {
kinds <- c(34L,92L,47L,98L,102L,110L,114L,116L)
decoded <- c(34L,92L,47L,8L,12L,10L,13L,9L)
at <- match(kind,kinds)
stopifnot(!is.na(at))
byte <- decoded[at]
}
}
stopifnot(byte<=127L)
bytes <- c(bytes,byte)
}
bytes
}
read_quantity <- function() {
space()
remaining <- intToUtf8(input[position:length(input)])
token <- regmatches(remaining,regexpr("^-?[0-9]+(\\.[0-9]+)?([eE][+-]?[0-9]+)?",remaining))
stopifnot(length(token)==1L,nchar(token)>0L)
position <<- position+nchar(token)
value <- as.numeric(token)
stopifnot(is.finite(value),value==floor(value),abs(value)<=9007199254740991)
value
}
quote_name <- function(bytes) {
pieces <- character()
short <- c('\\"','\\\\','\\b','\\f','\\n','\\r','\\t')
codes <- c(34L,92L,8L,12L,10L,13L,9L)
for(byte in bytes) {
at <- match(byte,codes)
part <- if(!is.na(at)) short[at] else if(byte<32L) sprintf('\\u%04x',byte) else intToUtf8(byte)
pieces <- c(pieces,part)
}
paste0('"',paste(pieces,collapse=""),'"')
}
totals <- new.env(hash=TRUE,parent=emptyenv())
names_by_key <- new.env(hash=TRUE,parent=emptyenv())
take(91L)
space()
if(peek()!=93L) {
repeat {
take(91L)
name <- read_name()
take(44L)
quantity <- read_quantity()
take(93L)
# Fixed-width hexadecimal preserves ASCII lexicographic ordering.
key <- paste0("k",paste(sprintf("%02x",name),collapse=""))
old <- if(exists(key,envir=totals,inherits=FALSE)) totals[[key]] else 0
totals[[key]] <- old+quantity
names_by_key[[key]] <- name
space()
if(peek()!=44L) break
position <<- position+1L
}
}
take(93L)
space()
stopifnot(position>length(input))
result <- character()
for(key in sort(ls(totals,all.names=TRUE),method="radix")) {
if(totals[[key]]>0) {
result <- c(result,paste0('[',quote_name(names_by_key[[key]]),',',sprintf('%.0f',totals[[key]]),']'))
}
}
cat('[',paste(result,collapse=','),']\n',sep='')
입력은 JSON 값 하나입니다. exercise.js부터 시작해 잠금 해제된 파일을 수정하세요. 표시된 잠금 파일 driver.js는 solve(input)을 호출하고, 그 반환값을 간결한 JSON으로 출력한 뒤 줄바꿈 하나를 출력합니다. 진단용 출력을 추가하지 마세요. 테스트는 전체 출력을 비교합니다. 모든 숫자 입력과 계산된 정수 합계는 안전한 정수 범위 내에 있습니다.
입력 예시:
[["pen",3],["book",1],["pen",-1]]예상 출력:
[["book",1],["pen",2]]직접 해보기
import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// stdin으로 JSON 값 하나가 들어옵니다. 데이터를 반환하고, solve 안에서는 출력하지 마세요.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));
R 개발자를 위한 JavaScript의 모든 레슨
직접 연습해 보세요: 온라인 JavaScript 컴파일러