Menu
CoddyTech

Final: Sensor Port

Lesson 48 of 48 in Coddy's Ruby for Python 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.

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

import re
import sys
class Above:
    def __init__(self, limit):
        self.limit = limit
    def accepts(self, value):
        return value > self.limit
class Sensor:
    def __init__(self, policy):
        self.policy = policy
        self.accepted = 0
        self.invalid = 0
        self.total = 0
    def feed(self, token):
        if re.fullmatch(r"[+-]?[0-9]+", token) is None:
            self.invalid += 1
            return
        value = int(token)
        if abs(value) > 1000000:
            self.invalid += 1
        elif self.policy.accepts(value):
            self.accepted += 1
            self.total += value
    def summary(self):
        return f"{self.accepted} {self.invalid} {self.total}"
lines = sys.stdin.read().splitlines()
sensor = Sensor(Above(int(lines[0])))
for token in lines[1:]:
    sensor.feed(token)
print(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 Python Developers

Practice on your own: Online Ruby compiler