Menu
CoddyTech

Final: Stock Ledger

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

challenge icon

Challenge

Medium

Port the complete R reference into the supplied Rust API. R status returns become explicit Rust Result values; environment-held stock closures become owned Rust state. Input has up to 100 name delta rows, names lowercase ASCII words of at most 31 bytes and deltas from -1000 to 1000. Empty input is valid. Stock::new() -> Stock starts at zero; quantity(&self) -> i32 reads it; apply(&mut self, delta: i32) -> Result<(), &'static str> rejects a negative resulting quantity with Err("negative"), leaving state unchanged. Ledger::new() -> Ledger starts empty; its apply(&mut self, name: &str, delta: i32) has the same result contract, and must not create a missing item when rejecting. quantity(&self, name: &str) -> Option<i32> distinguishes missing from zero. report(&self) -> String lists only positive stocks as name:quantity in name order, separated by newlines, or empty. Return rejected:N, then the report on following lines. Calls to report do not change state. The R environment stores stock closures with mutable captured quantities; Rust should own names and stock values in a map. Preserve the distinction between a missing item and an item with zero quantity.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

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

Complete R reference for the same valid input contract:

new_stock <- function() {
  amount <- 0
  list(quantity = function() amount,
       apply = function(delta) {
         candidate <- amount + delta
         if (candidate < 0) return(FALSE)
         amount <<- candidate
         TRUE
       })
}
new_ledger <- function() {
  entries <- new.env(hash = TRUE, parent = emptyenv())
  list(apply = function(name, delta) {
         present <- exists(name, envir = entries, inherits = FALSE)
         stock <- if (present) get(name, envir = entries, inherits = FALSE) else new_stock()
         if (!stock$apply(delta)) return(FALSE)
         if (!present) assign(name, stock, envir = entries)
         TRUE
       },
       quantity = function(name) {
         if (!exists(name, envir = entries, inherits = FALSE)) return(NULL)
         get(name, envir = entries, inherits = FALSE)$quantity()
       },
       report = function() {
         names <- sort(ls(entries, all.names = TRUE), method = "radix")
         rows <- character()
         for (name in names) {
           amount <- get(name, envir = entries, inherits = FALSE)$quantity()
           if (amount > 0) rows <- c(rows, paste0(name, ":", sprintf("%.0f", amount)))
         }
         if (length(rows) == 0L) "empty" else paste(rows, collapse = "\n")
       })
}
text <- trimws(paste(readLines(file("stdin"), warn = FALSE), collapse = "\n"))
words <- if (nchar(text) == 0L) character() else strsplit(text, "[[:space:]]+")[[1L]]
ledger <- new_ledger()
rejected <- 0L
if (length(words) > 0L) {
  for (index in seq.int(1L, length(words), by = 2L)) {
    if (!ledger$apply(words[index], as.numeric(words[index + 1L]))) rejected <- rejected + 1L
  }
}
cat("rejected:", rejected, "\n", ledger$report(), "\n", sep = "")

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod stock;
mod ledger;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
let mut s = stock::Stock::new(); assert_eq!(s.quantity(), 0);
    s.apply(11).unwrap(); assert_eq!(s.apply(-12), Err("negative")); assert_eq!(s.quantity(), 11);
    s.apply(-11).unwrap(); assert_eq!(s.quantity(), 0);
    let mut l = ledger::Ledger::new(); assert_eq!(l.quantity("held"), None);
    assert_eq!(l.apply("held", -8), Err("negative")); assert_eq!(l.quantity("held"), None);
    l.apply("held", 17).unwrap(); l.apply("alpha", 2).unwrap();
    assert_eq!(l.apply("held", -18), Err("negative")); assert_eq!(l.quantity("held"), Some(17));
    assert_eq!(l.report(), "alpha:2\nheld:17"); assert_eq!(l.report(), "alpha:2\nheld:17");
    l.apply("alpha", -2).unwrap(); assert_eq!(l.quantity("alpha"), Some(0)); assert_eq!(l.report(), "held:17");
    assert_eq!(ledger::Ledger::new().report(), "empty");
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}

All lessons in Rust for R Developers

Practice on your own: Online Rust compiler