Finale: Porting inventario
Lezione 47 di 48 del corso Ruby per sviluppatori R di Coddy.
Sfida
FacileAdatta il programma di riferimento. La scorta parte da zero; change(delta) accetta una modifica solo se la scorta risultante è non negativa, restituendo true o false. quantity legge la scorta. Inventory.change(code,delta) applica le modifiche per ciascun codice, creando un codice solo in caso di successo. report restituisce le quantità positive in ordine alfabetico di codice, come coppie code:quantity, oppure none. L’input è composto da coppie code delta, una per riga. L’output contiene un booleano per ogni modifica, seguito dal report. Fornisci Stock e Inventory in file separati.
Restituisci il testo da solve(input) senza stamparlo. Il driver bloccato stampa il testo restituito con un singolo a capo finale e verifica in modo indipendente le API pubbliche richieste.
Il tuo codice va in exercise.rb, stock.rb, inventory.rb. main.rb contiene il codice fornito per l’input/output e non può essere modificato.
Programma di riferimento in R. Riproduci il suo comportamento usando le API Ruby richieste.
normalize <- function(text) {
negative <- startsWith(text,"-")
text <- sub("^[+-]","",text)
text <- sub("^0+","",text)
if(!nzchar(text)) return("0")
if(negative) paste0("-",text) else text
}
compare_abs <- function(a,b) {
if(nchar(a)!=nchar(b)) return(sign(nchar(a)-nchar(b)))
ad <- utf8ToInt(a); bd <- utf8ToInt(b)
different <- which(ad!=bd)
if(!length(different)) 0 else sign(ad[different[1]]-bd[different[1]])
}
add_abs <- function(a,b) {
ad <- rev(utf8ToInt(a)-48L); bd <- rev(utf8ToInt(b)-48L)
size <- max(length(ad),length(bd))
length(ad) <- size; length(bd) <- size
ad[is.na(ad)] <- 0L; bd[is.na(bd)] <- 0L
out <- integer(size+1L); carry <- 0L
for(i in seq_len(size)) {
value <- ad[i]+bd[i]+carry
out[i] <- value %% 10L
carry <- as.integer(value>=10L)
}
out[size+1L] <- carry
normalize(paste(rev(out),collapse=""))
}
subtract_abs <- function(a,b) {
ad <- rev(utf8ToInt(a)-48L); bd <- rev(utf8ToInt(b)-48L)
length(bd) <- length(ad); bd[is.na(bd)] <- 0L
out <- integer(length(ad)); borrow <- 0L
for(i in seq_along(ad)) {
value <- ad[i]-bd[i]-borrow
borrow <- as.integer(value<0L)
out[i] <- if(value<0L) value+10L else value
}
normalize(paste(rev(out),collapse=""))
}
add_decimal <- function(a,b) {
a <- normalize(a); b <- normalize(b)
an <- startsWith(a,"-"); bn <- startsWith(b,"-")
av <- sub("^-","",a); bv <- sub("^-","",b)
if(an==bn) {
value <- add_abs(av,bv)
return(if(an && value!="0") paste0("-",value) else value)
}
order <- compare_abs(av,bv)
if(order==0) return("0")
value <- if(order>0) subtract_abs(av,bv) else subtract_abs(bv,av)
negative <- if(order>0) an else bn
if(negative) paste0("-",value) else value
}
new_stock <- function() {
quantity <- "0"
list(
change=function(delta) {
next_value <- add_decimal(quantity,delta)
if(startsWith(next_value,"-")) return(FALSE)
quantity <<- next_value
TRUE
},
quantity=function() quantity
)
}
new_inventory <- function() {
items <- new.env(hash=TRUE,parent=emptyenv())
list(
change=function(code,delta) {
stock <- if(exists(code,items,inherits=FALSE)) get(code,items) else new_stock()
if(!stock$change(delta)) return(FALSE)
assign(code,stock,items)
TRUE
},
report=function() {
keys <- sort(ls(items,all.names=TRUE),method="radix")
parts <- character()
for(key in keys) {
quantity <- get(key,items)$quantity()
if(quantity!="0") parts <- c(parts,paste0(key,":",quantity))
}
if(!length(parts)) "none" else paste(parts,collapse=" ")
}
)
}
inventory <- new_inventory()
lines <- readLines(file("stdin"),warn=FALSE)
for(line in lines) {
line <- trimws(line)
if(!nzchar(line)) next
parts <- strsplit(line,"[[:space:]]+")[[1]]
cat(if(inventory$change(parts[1],parts[2])) "true" else "false","\n",sep="")
}
cat(inventory$report(),"\n",sep="")
Provalo tu
require_relative 'exercise'
require_relative 'stock'
require_relative 'inventory'
def check(value)
raise 'Public API check failed' unless value
end
s = Stock.new
check(!s.change(-1) && s.quantity == 0 && s.change(4) && !s.change(-5) && s.quantity == 4)
i = Inventory.new
check(!i.change("x", -2) && i.report == "none")
check(i.change("b", 2) && i.change("a", 1) && i.report == "a:1 b:2")
puts solve(STDIN.read)
Tutte le lezioni di Ruby per sviluppatori R
1Inizia con Ruby
Eseguire file RubyOutput e commentiNomi e oggettiAritmetica con interiVerità e logica booleanaOperazioni sulle stringheSimboli e chiaviRiepilogo: bolla di accompagnamento2Flusso e metodi
Valori condizionaliCasi e intervalliCicli e uscita anticipataMetodi e valori restituitiValori predefiniti e parole chiaveRipasso: esecuzione del sensoreEsercitati da solo: Compilatore Ruby online