Recap: Charge Gate
Lesson 11 of 48 in Coddy's Rust for Python Developers course.
Challenge
EasySimulate a charge gate. Input is a whitespace-separated sequence of integers: initial charge followed by zero or more requested costs. Initial charge and each cost range from 0 to 100. Required API: pub fn can_pay(charge: i32, cost: i32) -> bool is true exactly when cost is nonnegative and no greater than charge. pub fn pay(charge: i32, cost: i32) -> i32 returns charge minus cost when affordable, otherwise the unchanged charge. Negative costs are rejected by both APIs even though stdin costs are nonnegative. Process costs in order and count accepted requests, including a zero-cost request. Output remaining accepted. Implement the public API in gate.rs. The supplied exercise.rs parses valid input and calls that API. Return the specified text without a trailing newline; the locked driver adds one newline. Do not print from the API. All input values satisfy the stated bounds.
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, gate.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 gate;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
assert!(gate::can_pay(17, 9));
assert_eq!(gate::pay(17, 9), 8);
assert!(!gate::can_pay(8, 9));
assert_eq!(gate::pay(8, 9), 8);
assert!(!gate::can_pay(8, -1));
assert_eq!(gate::pay(8, -1), 8);
assert!(gate::can_pay(0, 0));
assert_eq!(gate::pay(0, 0), 0);
assert_eq!(gate::pay(17, 9), 8);
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
All lessons in Rust for Python Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap2Decisions and Loops
Boolean ConditionsIf ExpressionsMatch and EnumsLoops and RangesRecap: Charge Gate3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler