Menu
CoddyTech

Receiptの状態の振り返り

Coddyの「Swift開発者のためのRust」コースのレッスン 35/48。

challenge icon

チャレンジ

簡単

line::Lineを実装し、公開フィールドとしてlabel: String、unit: i32、count: i32を用意してください。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の組を最大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));
}

Swift開発者のためのRustのすべてのレッスン

自分で練習してみよう: Rustオンラインコンパイラ