Menu
CoddyTech

Receipt State Recap

Lesson 35 of 48 in Coddy's Rust for Java Developers course.

challenge icon

Challenge

Easy

Implement line::Line with public label: String, unit: i32, and count: i32 fields. Implement receipt::Receipt::new() -> Receipt, add(&mut self, line: Line) -> bool, total(&self) -> i32, and labels(self) -> Vec<String>. Accept a line only when both numeric fields are nonnegative; rejection leaves existing state unchanged. Accepted lines contribute unit * count, and labels preserve insertion order and duplicates. labels consumes the receipt. solve reads complete whitespace-separated label unit count triples with integers between -100 and 100, at most 100 triples. Return the number of accepted lines and total as accepted:n total:n, then a newline and comma-separated accepted labels, or empty.

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, line.rs, receipt.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod line;
mod receipt;
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 r = receipt::Receipt::new(); assert_eq!(r.total(), 0);
assert!(r.add(line::Line { label: "ink".to_string(), unit: 13, count: 7 }));
assert!(!r.add(line::Line { label: "bad".to_string(), unit: -1, count: 3 }));
assert!(!r.add(line::Line { label: "bad2".to_string(), unit: 2, count: -3 }));
assert_eq!(r.total(), 91);
assert!(r.add(line::Line { label: "ink".to_string(), unit: 0, count: 5 }));
assert_eq!(r.total(), 91); assert_eq!(r.labels(), vec!["ink".to_string(), "ink".to_string()]);
assert!(receipt::Receipt::new().labels().is_empty());
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}

All lessons in Rust for Java Developers

Practice on your own: Online Rust compiler