Abschluss: Sensor-Richtlinien
Lektion 48 von 48 im Kurs Rust für JavaScript-Entwickler von Coddy.
Aufgabe
MittelPortiere la riferimento JavaScript sostituendo il contratto di policy basato sul duck typing con un trait Rust implementato esplicitamente. L’input inizia con una soglia intera i32, seguita da al massimo 100 token di lettura separati da spazi. Un token contiene al massimo 31 byte ASCII. Le letture valide hanno un segno iniziale facoltativo e cifre decimali e rientrano in i32; ogni totale parziale rientra in i32. reading::parse(text: &str) -> Result<i32, &'static str> accetta il token completo senza spazi circostanti e restituisce Err("invalid") per qualsiasi altra cosa. Accept::accept(&self, value: i32) -> bool è il contratto della policy. Above::new(limit: i32) -> Above accetta i valori strettamente maggiori. Report::new() -> Report parte vuoto; feed<R: Accept + ?Sized>(&mut self, value: i32, rule: &R) aggiunge le letture accettate al conteggio e al totale, mantenendo lo stato invariato per le letture rifiutate; count(&self) -> usize e total(&self) -> i32 sono metodi di osservazione. Deve funzionare qualsiasi policy Accept definita dal chiamante, incluso un oggetto trait. Produci count total invalid, usando Above per elaborare l’input. Se non ci sono letture, il risultato è 0 0 0.
Implementa le API esportate richieste e restituisci il risultato da exercise::solve(input: &str) -> String senza un a capo finale. Non stampare nel codice modificabile. Il driver bloccato verifica le API richieste indipendentemente, legge tutto stdin e stampa il testo restituito con un a capo finale.
Il tuo codice va in exercise.rs, rule.rs, above.rs, report.rs, reading.rs. main.rs contiene il codice fornito per input e output e non può essere modificato.
I chiamanti JavaScript possono passare qualsiasi oggetto con un metodo accept, incluso un oggetto letterale, e la forma dell’oggetto non viene verificata finché feed non lo chiama. I chiamanti Rust forniscono un tipo con un’implementazione esplicita del trait o un oggetto trait compatibile. Il riferimento verifica i token decimali completi e l’intervallo con segno a 32 bit; il solo parseInt accetterebbe prefissi non validi. JavaScript number è esatto per i limiti indicati dei totali parziali.
Programma di riferimento JavaScript autonomo completo:
// Standalone JavaScript reference for Node. No packages or unchecked numeric prefixes.
"use strict";
// A reading is {ok: true, value} or {ok: false, reason: "invalid"}.
function parse(text) {
if (text.trim() !== text || !/^[+-]?[0-9]+$/.test(text)) return { ok: false, reason: "invalid" };
const value = Number(text);
if (!Number.isInteger(value) || value < -2147483648 || value > 2147483647) {
return { ok: false, reason: "invalid" };
}
return { ok: true, value };
}
// A policy is any object with an accept(value) method that returns a boolean.
class Above {
#limit;
constructor(limit) { this.#limit = limit; }
accept(value) { return value > this.#limit; }
}
class Report {
#accepted = 0;
#sum = 0;
feed(value, rule) {
if (rule.accept(value)) {
this.#accepted++;
this.#sum += value;
}
}
count() { return this.#accepted; }
total() { return this.#sum; }
}
function solve(input) {
const words = input.trim().split(/\s+/);
const policy = new Above(Number(words[0]));
const report = new Report();
let invalid = 0;
for (const word of words.slice(1)) {
const reading = parse(word);
if (reading.ok) report.feed(reading.value, policy);
else invalid++;
}
return `${report.count()} ${report.total()} ${invalid}`;
}
module.exports = { parse, Above, Report, solve };
if (require.main === module) {
process.stdout.write(solve(require("fs").readFileSync(0, "utf8")) + "\n");
}
Probier es selbst
#![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();
// BEGINN DER TESTS DER ÖFFENTLICHEN 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);
// ENDE DER TESTS DER ÖFFENTLICHEN API
println!("{}", exercise::solve(&input));
}
Alle Lektionen in Rust für JavaScript-Entwickler
1Erste Rust-Programme
Rust-Module ausführenAusgabe und KommentareModule und SichtbarkeitBindungen und TypenZahlen und TypumwandlungenRückblick: Speicherrechnung4Besitz und Ausleihen
Besitz und VerschiebenGemeinsame AusleihenVeränderbare AusleihenLebensdauern und AnsichtenWiederholung: Ausleihen2Entscheidungen und Schleifen
Boolesche BedingungenIf-AusdrückeMatch und EnumsSchleifen und BereicheRückblick: LadetorÜbe selbstständig: Online-Rust-Compiler