Menu
CoddyTech

Final: Inventory Port

Lesson 47 of 48 in Coddy's Ruby for Dart 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.

Input bounds: at most 1000 data lines. Inventory codes contain only lowercase ASCII letters, and each inventory delta is between -1000000 and 1000000. For the sensor port, the first-line limit is between -1000000 and 1000000; token validity follows the parser contract above.

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

import 'dart:io';
class Stock {
  int quantity=0;
  bool change(int delta) {
    final next=quantity+delta;
    if(next<0)return false;
    quantity=next;return true;
  }
}
class Inventory {
  final items=<String,Stock>{};
  bool change(String code,int delta) {
    final stock=items[code]??Stock();
    if(!stock.change(delta))return false;
    items[code]=stock;return true;
  }
  String report() {
    final codes=items.keys.where((code)=>items[code]!.quantity>0).toList()..sort();
    return codes.isEmpty?'none':codes.map((code)=>code+':'+items[code]!.quantity.toString()).join(' ');
  }
}
void main() {
  final inventory=Inventory();
  String? line;
  while((line=stdin.readLineSync())!=null) {
    final text=line!.trim();
    if(text.isEmpty)continue;
    final parts=text.split(RegExp(r'\s+'));
    print(inventory.change(parts[0],int.parse(parts[1])));
  }
  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 Dart Developers

Practice on your own: Online Ruby compiler