Final: Port do Inventário
Lição 47 de 48 do curso Ruby para desenvolvedores R da Coddy.
Desafio
FácilAdapte o programa de referência. O estoque começa em zero; change(delta) aceita uma alteração somente se o estoque resultante não for negativo, retornando true ou false. quantity lê o estoque. Inventory.change(code,delta) aplica alterações por código, criando um código somente em caso de sucesso. report retorna as quantidades positivas em ordem alfabética de código, como pares code:quantity, ou none. A entrada consiste em pares de código e delta, um por linha. A saída contém um booleano por alteração, seguido do relatório. Forneça Stock e Inventory em seus próprios arquivos.
Retorne o texto de solve(input) sem imprimir. O driver bloqueado imprime o texto retornado com uma quebra de linha final e verifica as APIs públicas obrigatórias separadamente.
Seu código deve ficar em exercise.rb, stock.rb, inventory.rb. main.rb contém o código fornecido de entrada/saída e não pode ser editado.
Programa de referência em R. Reproduza seu comportamento usando as APIs Ruby obrigatórias.
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="")
Experimente você mesmo
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)
Todas as lições de Ruby para desenvolvedores R
1Comece com Ruby
Execute arquivos RubySaída e comentáriosNomes e objetosAritmética de inteirosVerdade e lógica booleanaOperações com stringsSímbolos e chavesRevisão: Romaneio2Fluxo e métodos
Valores condicionaisCase e intervalosLaços e saída antecipadaMétodos e retornosValores padrão e palavras-chaveRevisão: execução do sensorPratique por conta própria: Compilador de Ruby online