Menu
CoddyTech

Chuyển một sổ cái R

Bài học 47 trên 48 trong khóa học JavaScript dành cho người dùng R của Coddy.

challenge icon

Thử thách

Dễ

Chuyển chương trình tham chiếu R đi kèm sang JavaScript. Đầu vào là một mảng gồm các cặp [name,quantity]; tên là chuỗi và số lượng là số nguyên. Tính tổng số lượng theo tên, chỉ giữ lại các tổng dương, sắp xếp tên theo thứ tự ASCII rồi trả về các cặp [name,total]. Dùng Map để các tên giống thuộc tính của prototype vẫn hoạt động. Tên chỉ chứa ký tự ASCII.

Chương trình tham chiếu bằng R. Bộ điều hợp JSON dành riêng cho hợp đồng giữ tên ASCII dưới dạng giá trị byte, kể cả NUL được nhúng, đồng thời dùng khóa môi trường dạng thập lục phân để tra cứu an toàn và sắp xếp ASCII. Giá trị double giữ nguyên các tổng số nguyên an toàn như đã nêu trong tài liệu. Chương trình đọc một giá trị JSON và in 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='')

Đầu vào là một giá trị JSON. Chỉnh sửa các tệp chưa khóa, bắt đầu với exercise.js. Tệp driver.js bị khóa và hiển thị sẽ gọi solve(input), rồi in giá trị trả về dưới dạng JSON thu gọn, theo sau là một ký tự xuống dòng. Đừng thêm đầu ra chẩn đoán. Các bài kiểm tra so sánh toàn bộ đầu ra. Tất cả số đầu vào và tổng số nguyên được tính đều nằm trong phạm vi số nguyên an toàn.

Ví dụ đầu vào:

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

Đầu ra mong đợi:

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

Tự làm thử

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// Một giá trị JSON được đưa vào qua stdin. Trả về dữ liệu; đừng in ra trong solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

Tất cả bài học trong JavaScript dành cho người dùng R

Tự luyện tập: Trình biên dịch JavaScript online