最终:传感器策略
Coddy 面向 Java 开发者的 Rust 课程的第 48 课,共 48 课。
挑战
中等将 Java 参考实现移植过来,把其中的 Accept 接口参数替换为所需的借用 Rust trait 约束。输入以一个 i32 整数阈值开头,后面最多有 100 个由空白字符分隔的读数标记。每个标记最多为 31 个 ASCII 字节。有效读数可以带可选的前导符号,由十进制数字组成,并且能表示为 i32;每次累计总和都能表示为 i32。reading::parse(text: &str) -> Result<i32, &'static str> 接受不带前后空格的完整标记,其他任何输入都会返回 Err("invalid")。Accept::accept(&self, value: i32) -> bool 是策略约定。Above::new(limit: i32) -> Above 接受严格大于阈值的值。Report::new() -> Report 创建空报告;feed<R: Accept + ?Sized>(&mut self, value: i32, rule: &R) 会将符合条件的读数加入计数和总和,并在读数不符合条件时保留原状态;count(&self) -> usize 和 total(&self) -> i32 是查询方法。任何由调用方定义的 Accept 策略都必须可用,包括 trait 对象。使用 Above 处理输入,并输出 count total invalid。没有读数时,输出为 0 0 0。
实现所需的导出 API,并从 exercise::solve(input: &str) -> String 返回结果,末尾不带换行符。不要在可编辑代码中打印内容。锁定的驱动程序会单独检查所需 API,读取全部标准输入,并在返回的文本后添加一个换行符后打印。
你的代码应写在 exercise.rs、rule.rs、above.rs、report.rs 和 reading.rs 中。main.rs 包含提供的输入输出代码,不能编辑。
Java 使用 Accept 接口并捕获 NumberFormatException;Rust 使用提供的 trait 和 Result 值。参考实现会先检查 ASCII 十进制语法,再进行 Java 解析,因此不会误接受 Unicode 数字。除了提供的阈值类之外,还要支持调用方定义的策略。
以下是针对相同有效输入约定的完整 Java 17 参考实现:
import java.util.Scanner;
class Main {
interface Accept { boolean accept(int value); }
static final class Above implements Accept {
private final int limit;
Above(int limit) { this.limit = limit; }
public boolean accept(int value) { return value > limit; }
}
static final class Report {
private int count;
private int total;
void feed(int value, Accept rule) {
if (rule.accept(value)) { count++; total += value; }
}
int count() { return count; }
int total() { return total; }
}
static int parse(String token) throws NumberFormatException {
if (!token.matches("[+-]?[0-9]+")) throw new NumberFormatException("invalid");
return Integer.parseInt(token);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Accept rule = new Above(input.nextInt());
Report report = new Report();
int invalid = 0;
while (input.hasNext()) {
String token = input.next();
try { report.feed(parse(token), rule); }
catch (NumberFormatException error) { invalid++; }
}
System.out.println(report.count() + " " + report.total() + " " + invalid);
}
}亲手试试
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod rule;
mod above;
mod report;
mod reading;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 开始公开 API 测试
use rule::Accept;
let p=above::Above::new(-3); assert!(p.accept(-2)); assert!(!p.accept(-3)); assert!(!p.accept(-4));
assert_eq!(reading::parse("+17"), Ok(17)); assert_eq!(reading::parse("-0"), Ok(0));
for s in &["", "+", " 3", "2x", "2147483648"] { assert_eq!(reading::parse(s), Err("invalid")); }
struct Odd;
impl rule::Accept for Odd { fn accept(&self, value: i32) -> bool { value % 2 != 0 } }
let policy: &dyn rule::Accept=&Odd;
let mut r=report::Report::new(); assert_eq!(r.count(),0); assert_eq!(r.total(),0);
r.feed(-7,policy); r.feed(4,policy); r.feed(9,policy);
assert_eq!(r.count(),2); assert_eq!(r.total(),2);
r.feed(0,policy); assert_eq!(r.count(),2); assert_eq!(r.total(),2);
r.feed(1,&p); assert_eq!(r.count(),3); assert_eq!(r.total(),3);
assert_eq!(report::Report::new().count(),0);
// 结束公开 API 测试
println!("{}", exercise::solve(&input));
}
面向 Java 开发者的 Rust中的所有课
自己练习: Rust 在线编译器