Menu
CoddyTech

הסבת פנקס חשבונות ב־R

שיעור 47 מתוך 48 בקורס JavaScript למפתחי R של Coddy.

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";
// ערך JSON אחד מתקבל דרך stdin. החזירו נתונים; אל תדפיסו מתוך solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

כל השיעורים ביחידה JavaScript למפתחי R

תרגלו בעצמכם: קומפיילר JavaScript אונליין