Menu
CoddyTech

Final: Sensor Port

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

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

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
static int read_line(char **out,size_t *length_out) {
    size_t length=0,capacity=64;
    char *line=malloc(capacity);
    if(!line)return -1;
    int ch;
    while((ch=getchar())!=EOF && ch!='\n') {
        if(length+1>=capacity) {
            if(capacity>SIZE_MAX/2){free(line);return -1;}
            capacity*=2;
            char *grown=realloc(line,capacity);
            if(!grown){free(line);return -1;}
            line=grown;
        }
        line[length++]=(char)ch;
    }
    if(ch==EOF && length==0){free(line);return ferror(stdin)?-1:0;}
    if(length && line[length-1]=='\r')--length;
    line[length]='\0';*out=line;
    if(length_out)*length_out=length;
    return 1;
}

struct Above {int limit;};
struct Policy {bool (*accepts)(const void *,int);const void *context;};
static bool above_accepts(const void *context,int value) {
    const struct Above *above=context;
    return value>above->limit;
}
struct Sensor {struct Policy policy;long long accepted,invalid,total;};
static bool parse_token(const char *token,size_t length,int *out) {
    bool negative=false;
    size_t i=0;
    if(i<length && (token[i]=='+' || token[i]=='-'))negative=token[i++]=='-';
    if(i==length)return false;
    int value=0;
    for(;i<length;++i) {
        if(token[i]<'0' || token[i]>'9')return false;
        int digit=token[i]-'0';
        if(value>(1000000-digit)/10)return false;
        value=value*10+digit;
    }
    *out=negative?-value:value;return true;
}
static void sensor_feed(struct Sensor *sensor,const char *token,size_t length) {
    int value;
    if(!parse_token(token,length,&value)){++sensor->invalid;return;}
    if(sensor->policy.accepts(sensor->policy.context,value)) {
        ++sensor->accepted;sensor->total+=value;
    }
}
int main(void) {
    char *line=NULL;
    if(read_line(&line,NULL)!=1)return EXIT_FAILURE;
    struct Above above={(int)strtol(line,NULL,10)};free(line);
    struct Sensor sensor={{above_accepts,&above},0,0,0};
    int status;size_t length;
    while((status=read_line(&line,&length))>0){sensor_feed(&sensor,line,length);free(line);}
    if(status<0)return EXIT_FAILURE;
    printf("%lld %lld %lld\n",sensor.accepted,sensor.invalid,sensor.total);
    return 0;
}

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 C Developers

Practice on your own: Online Ruby compiler