レシートの状態の振り返り
Coddyの「GDScript開発者のための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> を実装してください。両方の数値フィールドが非負の場合にのみ行を受け入れ、拒否された場合は既存の状態を変更しないでください。受け入れられた行は unit * count を合計に加算し、ラベルは挿入順と重複を保持します。labels はレシートを消費します。solve は、整数が -100 から 100 までの、空白で区切られた完全な label unit count の3つ組を最大 100 個読み取ります。受け入れた行の数と合計を 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));
}
GDScript開発者のためのRustのすべてのレッスン
自分で練習してみよう: Rustオンラインコンパイラ