最终:传感器策略
Coddy 面向 Luau 开发者的 Rust 课程的第 48 课,共 48 课。
挑战
中等移植 Luau 参考实现,将其基于表方法的策略约定替换为显式实现的 Rust trait。输入以一个 i32 整数阈值开头,后面最多跟随 100 个由空白分隔的读数 token。每个 token 最多包含 31 个 ASCII 字节。有效读数可以带可选的前导符号,后面跟十进制数字,并且必须能放入 i32;每次累计总和都必须能放入 i32。reading::parse(text: &str) -> Result<i32, &'static str> 接受不含首尾空格的完整 token,其他任何内容都会返回 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 包含提供的输入输出代码,不能编辑。
Luau 调用方可以提供一个带有兼容接受方法的表。Rust 调用方则提供显式实现该 trait 的类型,或兼容的 trait 对象。参考实现会在累加数字前检查完整的 ASCII 十进制 token 和有符号 32 位范围;单独使用 tonumber 会接受更广泛的数字格式。在给定的累计总和范围内,Luau 的 number 是精确的。
完整的独立 Luau 参考程序:
-- Luau console reference with strict ASCII and i32 bounds.
local function parse(text: string): number?
if not text:match("^[+-]?[0-9]+$") then return nil end
local negative = text:sub(1, 1) == "-"
local first = (negative or text:sub(1, 1) == "+") and 2 or 1
local limit = negative and 2147483648 or 2147483647
local magnitude = 0
for index = first, #text do
local digit = text:byte(index) - 48
if magnitude > math.floor((limit - digit) / 10) then return nil end
magnitude = magnitude * 10 + digit
end
return negative and -magnitude or magnitude
end
local Above = {}
Above.__index = Above
function Above.new(limit) return setmetatable({limit = limit}, Above) end
function Above:accept(value) return value > self.limit end
local Report = {}
Report.__index = Report
function Report.new() return setmetatable({count = 0, total = 0}, Report) end
function Report:feed(value, rule)
if rule:accept(value) then
self.count = self.count + 1
self.total = self.total + value
end
end
local words = {}
for word in io.read("*a"):gmatch("%S+") do words[#words + 1] = word end
local rule, report, invalid = Above.new(tonumber(words[1])), Report.new(), 0
for index = 2, #words do
local value = parse(words[index])
if value == nil then invalid = invalid + 1 else report:feed(value, rule) end
end
print(string.format("%d %d %d", 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));
}
面向 Luau 开发者的 Rust中的所有课
自己练习: Rust 在线编译器