Menu
CoddyTech

R製の台帳を移植する

Coddyの「R開発者のためのJavaScript」コースのレッスン 47/48。

challenge icon

チャレンジ

簡単

付属のR参照プログラムをJavaScriptに移植してください。入力は[name,quantity]ペアの配列です。nameは文字列、quantityは整数です。nameごとにquantityを合計し、正の合計値だけを残して、nameをASCII順に並べ、[name,total]ペアを返してください。Mapを使うことで、プロトタイプに似た名前も正しく扱えます。nameにはASCII文字のみが含まれます。

Rの参照プログラムです。契約固有のJSONアダプターは、埋め込みNULを含め、ASCIIの名前をバイト値として保持し、安全に検索してASCII順に並べるために16進数の環境キーを使います。double値は、文書化された安全な整数の合計値を保持します。JSON値を1つ読み取り、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値1つです。ロックされていないファイルを編集してください。まずexercise.jsから始めます。表示されているロック済みのdriver.jsはsolve(input)を呼び出し、その戻り値をコンパクトなJSONとして出力し、最後に改行を1つ付けます。診断用の出力を追加しないでください。テストでは出力全体を比較します。すべての数値入力と計算後の整数の合計値は、安全な整数の範囲内に収まります。

入力例:

[["pen",3],["book",1],["pen",-1]]

期待される出力:

[["book",1],["pen",2]]

自分で試してみよう

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// stdin から JSON 値が1つ入力されます。データを返し、solve 内では出力しないでください。
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

R開発者のためのJavaScriptのすべてのレッスン

自分で練習してみよう: JavaScriptオンラインコンパイラ