Menu
CoddyTech

レシート状態の振り返り

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

challenge icon

チャレンジ

簡単

公開フィールド 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 の組をすべて読み取ります。組は最大 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();
    // 公開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());
    // 公開APIの検証終了
    println!("{}", exercise::solve(&input));
}

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

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