Final: Inventory Port
Lesson 47 of 48 in Coddy's Ruby for Rust Developers course.
Challenge
EasyPort 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.
Rust reference program. Match its behavior using the required Ruby APIs.
use std::collections::BTreeMap;
use std::io::{self,Read};
#[derive(Default)]
struct Stock{quantity:i64}
impl Stock{
fn change(&mut self,delta:i64)->bool{
let next=self.quantity+delta;
if next<0{return false;}
self.quantity=next;true
}
}
#[derive(Default)]
struct Inventory{items:BTreeMap<String,Stock>}
impl Inventory{
fn change(&mut self,code:&str,delta:i64)->bool{
if let Some(stock)=self.items.get_mut(code){return stock.change(delta);}
let mut stock=Stock::default();
if !stock.change(delta){return false;}
self.items.insert(code.to_owned(),stock);true
}
fn report(&self)->String{
let parts:Vec<_>=self.items.iter().filter(|(_,stock)|stock.quantity>0)
.map(|(code,stock)|format!("{}:{}",code,stock.quantity)).collect();
if parts.is_empty(){"none".to_owned()}else{parts.join(" ")}
}
}
fn main(){
let mut input=String::new();io::stdin().read_to_string(&mut input).unwrap();
let mut inventory=Inventory::default();
for line in input.lines(){
let mut parts=line.split_whitespace();
if let Some(code)=parts.next(){
let delta=parts.next().unwrap().parse::<i64>().unwrap();
println!("{}",inventory.change(code,delta));
}
}
println!("{}",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 Rust Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: BorrowPractice on your own: Online Ruby compiler