Final: Sensor Port
Lesson 48 of 48 in Coddy's Ruby for Swift Developers course.
Challenge
EasyPort 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.
Swift reference program. Match its behavior using the required Ruby APIs.
protocol Policy {func accepts(_ value:Int)->Bool}
struct Above:Policy {
let limit:Int
func accepts(_ value:Int)->Bool {value>limit}
}
func parseToken(_ token:String)->Int? {
let bytes=Array(token.utf8)
var i=0
var negative=false
if i<bytes.count && (bytes[i]==43 || bytes[i]==45) {
negative=bytes[i]==45
i+=1
}
guard i<bytes.count else{return nil}
var value=0
while i<bytes.count {
guard bytes[i]>=48 && bytes[i]<=57 else{return nil}
let digit=Int(bytes[i])-48
guard value<=(1000000-digit)/10 else{return nil}
value=value*10+digit
i+=1
}
return negative ? -value : value
}
final class Sensor {
private let policy:any Policy
private var accepted=0
private var invalid=0
private var total=0
init(_ policy:any Policy){self.policy=policy}
func feed(_ token:String) {
guard let value=parseToken(token) else{invalid+=1;return}
if policy.accepts(value){accepted+=1;total+=value}
}
func summary()->String {
[accepted,invalid,total].map(String.init).joined(separator:" ")
}
}
let sensor=Sensor(Above(limit:Int(readLine()!)!))
while let token=readLine(){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 Swift Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: BorrowPractice on your own: Online Ruby compiler