Menu
CoddyTech

结课:传感器策略

Coddy 面向 Lua 开发者的 Rust 课程的第 48 课,共 48 课。

challenge icon

挑战

中等

将 Lua 参考实现移植过来,用显式的 Rust trait 替换其基于 table 方法的接受策略。Lua 的 nil 或整数解析结果对应 Rust 的 Result 值,并且 Lua 整数需要遵守与参考解析器相同的显式 i32 范围限制。输入以一个 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 包含提供的输入输出代码,不能编辑。

下面是适用于相同有效输入契约的完整 Lua 参考实现:

local function parse(text)
    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 > (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));
}

面向 Lua 开发者的 Rust中的所有课

自己练习: Rust 在线编译器