Menu
CoddyTech

Final: Sensor Port

Lesson 48 of 48 in Coddy's Ruby for Rust Developers course.

challenge icon

Challenge

Easy

Port the reference program. Above(limit)#accept?(n) accepts n strictly above limit. Sensor(policy)#feed(token) parses an optional sign followed by one or more ASCII digits, with no whitespace or other characters, and accepts only integers from -1000000 to 1000000. Invalid tokens increment invalid; valid tokens accepted by policy increment accepted and add to total. Rejected valid tokens change neither count. summary returns accepted invalid total separated by spaces. Input first line is the limit; each remaining line is one token with its line ending removed. All three counters start at zero. Custom policy objects must work.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb, above.rb, sensor.rb. main.rb holds the supplied input/output code and cannot be edited.

Input bounds: at most 1000 data lines. Inventory codes contain only lowercase ASCII letters, and each inventory delta is between -1000000 and 1000000. For the sensor port, the first-line limit is between -1000000 and 1000000; token validity follows the parser contract above.

Rust reference program. Match its behavior using the required Ruby APIs.

use std::io::{self,Read};
trait Policy{fn accepts(&self,value:i32)->bool;}
struct Above{limit:i32}
impl Policy for Above{fn accepts(&self,value:i32)->bool{value>self.limit}}
fn parse_token(token:&str)->Option<i32>{
    let bytes=token.as_bytes();let mut i=0;let mut negative=false;
    if let Some(&sign)=bytes.first(){
        if sign==b'+'||sign==b'-'{negative=sign==b'-';i+=1;}
    }
    if i==bytes.len(){return None;}
    let mut value=0;
    for &byte in &bytes[i..]{
        if !byte.is_ascii_digit(){return None;}
        let digit=i32::from(byte-b'0');
        if value>(1_000_000-digit)/10{return None;}
        value=value*10+digit;
    }
    Some(if negative{-value}else{value})
}
struct Sensor<P>{policy:P,accepted:i64,invalid:i64,total:i64}
impl<P:Policy> Sensor<P>{
    fn new(policy:P)->Self{Self{policy,accepted:0,invalid:0,total:0}}
    fn feed(&mut self,token:&str){
        match parse_token(token){
            None=>self.invalid+=1,
            Some(value) if self.policy.accepts(value)=>{
                self.accepted+=1;self.total+=i64::from(value);
            },
            Some(_)=>{}
        }
    }
    fn summary(&self)->String{format!("{} {} {}",self.accepted,self.invalid,self.total)}
}
fn main(){
    let mut input=String::new();io::stdin().read_to_string(&mut input).unwrap();
    let mut lines=input.lines();
    let limit=lines.next().unwrap().parse::<i32>().unwrap();
    let mut sensor=Sensor::new(Above{limit});
    for line in lines{sensor.feed(line);}
    println!("{}",sensor.summary());
}

Try it yourself

require_relative 'exercise'
require_relative 'above'
require_relative 'sensor'
def check(value)
  raise 'Public API check failed' unless value
end
check(Above.new(4).accept?(5) && !Above.new(4).accept?(4))
policy = Object.new
def policy.accept?(n); n.even?; end
s = Sensor.new(policy)
["2", "-4", "3", "x", "4\n", "1000001"].each { |t| s.feed(t) }
check(s.summary == "2 3 -2" && s.summary == "2 3 -2")

puts solve(STDIN.read)

All lessons in Ruby for Rust Developers

Practice on your own: Online Ruby compiler