Menu
CoddyTech

总结:库存程序移植

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

challenge icon

挑战

简单

移植参考程序。库存初始为 0;只有结果库存非负时,change(delta) 才接受更改,并返回 true 或 false。quantity 用于读取库存。Inventory.change(code,delta) 按代码应用更改,且只有操作成功时才创建该代码。report 按代码的字母顺序返回正数库存,格式为 code:quantity 对,若没有则返回 none。输入由 code delta 对组成,每行一对。输出每次更改对应的一个布尔值,然后输出报告。请将 Stock 和 Inventory 分别放在各自的文件中。

让 solve(input) 返回文本,不要打印。锁定的驱动程序会打印返回的文本,并在末尾添加一个换行符,同时独立检查所需的公共 API。

你的代码应写入 exercise.rb、stock.rb 和 inventory.rb。main.rb 中是提供的输入和输出代码,不能编辑。

R 参考程序。使用指定的 Ruby API 实现相同行为。

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="")

亲手试试

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)

面向 R 开发者的 Ruby中的所有课

自己练习: Ruby 在线编译器