Menu
CoddyTech

Final: Inventory Port

Lesson 47 of 48 in Coddy's Ruby for R Developers course.

challenge icon

Challenge

Easy

Port the reference program. Stock starts at zero; change(delta) accepts a change only if the resulting stock is nonnegative, returning true or false. quantity reads stock. Inventory.change(code,delta) applies changes per code, creating a code only on success. report returns positive quantities in alphabetic code order as code:quantity pairs, or none. Input consists of code delta pairs, one per line. Output one boolean per change, then report. Provide Stock and Inventory in their own files.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb, stock.rb, inventory.rb. main.rb holds the supplied input/output code and cannot be edited.

R reference program. Match its behavior using the required Ruby APIs.

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

Try it yourself

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)

All lessons in Ruby for R Developers

Practice on your own: Online Ruby compiler