レシート状態のまとめ
Coddyの「Kotlin開発者のためのRust」コースのレッスン 35/48。
チャレンジ
簡単公開フィールドlabel: String、unit: i32、count: i32を持つline::Lineを実装してください。receipt::Receipt::new() -> Receipt、add(&mut self, line: Line) -> bool、total(&self) -> i32、およびlabels(self) -> Vec<String>を実装してください。両方の数値フィールドが0以上の場合に限り、行を受け入れてください。拒否された場合、既存の状態は変更されません。受け入れられた行はunit * countを合計に加算し、ラベルは挿入順と重複を保持します。labelsはレシートを消費します。solveは、整数が-100から100の範囲で、最大100組までの、空白区切りのlabel unit countの組をすべて読み取ります。受け入れられた行数と合計をaccepted:n total:nとして返し、その後に改行と、カンマ区切りの受け入れられたラベルを続けてください。受け入れられたラベルがない場合はemptyを返します。
必要な公開APIを実装し、最終改行を付けずにexercise::solve(input: &str) -> Stringから結果を返してください。編集可能なコード内で出力してはいけません。ロックされたドライバーは必要なAPIを個別にチェックし、標準入力をすべて読み取り、返されたテキストを最後に改行を1つ付けて出力します。
コードはexercise.rs、line.rs、receipt.rsに記述してください。main.rsには提供された入出力コードがあり、編集できません。
自分で試してみよう
#![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();
// PUBLIC API の検証開始
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());
// PUBLIC API の検証終了
println!("{}", exercise::solve(&input));
}
Kotlin開発者のためのRustのすべてのレッスン
自分で練習してみよう: Rustオンラインコンパイラ