Menu
CoddyTech

移植 R 账本

Coddy 面向 R 开发者的 JavaScript 课程的第 47 课,共 48 课。

challenge icon

挑战

简单

将附带的 R 参考程序移植到 JavaScript。输入是由 [name,quantity] 对组成的数组;名称是字符串,数量是整数。按名称汇总数量,只保留正数总和,按 ASCII 顺序对名称排序,并返回 [name,total] 对。使用 Map,这样类似原型属性的名称也能正常处理。名称只包含 ASCII 字符。

R 参考程序。其符合约定的 JSON 适配器会将 ASCII 名称保留为字节值,包括嵌入的 NUL,并使用十六进制环境键来安全查找和按 ASCII 排序。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 在线编译器