Menu
CoddyTech

Final: Inventory Port

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

challenge icon

Challenge

Easy

Input bounds: at most 1000 nonblank data lines. Each inventory code contains only lowercase ASCII letters. Each delta is an integer between -1000000 and 1000000 inclusive.

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.

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

local Stock = {}
Stock.__index = Stock
function Stock.new() return setmetatable({quantity = 0}, Stock) end
function Stock:change(delta)
  if self.quantity + delta < 0 then return false end
  self.quantity = self.quantity + delta
  return true
end
local Inventory = {}
Inventory.__index = Inventory
function Inventory.new() return setmetatable({items = {}}, Inventory) end
function Inventory:change(code, delta)
  local stock = self.items[code] or Stock.new()
  if not stock:change(delta) then return false end
  self.items[code] = stock
  return true
end
function Inventory:report()
  local keys = {}
  for key, stock in pairs(self.items) do
    if stock.quantity > 0 then keys[#keys + 1] = key end
  end
  table.sort(keys)
  local parts = {}
  for _, key in ipairs(keys) do
    parts[#parts + 1] = key .. ":" .. string.format("%.0f", self.items[key].quantity)
  end
  return #parts == 0 and "none" or table.concat(parts, " ")
end
local inventory = Inventory.new()
for line in io.lines() do
  if string.match(line, "%S") then
    local code, delta = string.match(line, "^(%S+)%s+(%S+)")
    print(inventory:change(code, tonumber(delta)))
  end
end
print(inventory:report())

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 Lua Developers

Practice on your own: Online Ruby compiler