Final: Inventory Port
Lesson 47 of 48 in Coddy's Ruby for C Developers course.
Challenge
EasyPort the reference program. Stock starts at zero; change(delta) accepts a change only if the resulting stock is nonnegative, returning true or false. quantity reads stock. Inventory.change(code,delta) applies changes per code, creating a code only on success. report returns positive quantities in alphabetic code order as code:quantity pairs, or none. Input consists of code delta pairs, one per line. Output one boolean per change, then report. Provide Stock and Inventory in their own files.
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, stock.rb, inventory.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 Stock {long long quantity;};
static bool stock_change(struct Stock *stock,long long delta) {
long long next=stock->quantity+delta;
if(next<0)return false;
stock->quantity=next;return true;
}
struct Entry {char *code;struct Stock stock;};
struct Inventory {struct Entry entries[1000];size_t count;};
static bool inventory_change(struct Inventory *inventory,char *code,long long delta) {
size_t i=0;
while(i<inventory->count && strcmp(inventory->entries[i].code,code)!=0)++i;
if(i<inventory->count)return stock_change(&inventory->entries[i].stock,delta);
struct Stock stock={0};
if(!stock_change(&stock,delta))return false;
char *copy=malloc(strlen(code)+1);
if(!copy)exit(EXIT_FAILURE);
strcpy(copy,code);
inventory->entries[inventory->count++]=(struct Entry){copy,stock};
return true;
}
static int compare(const void *a,const void *b) {
return strcmp(((const struct Entry*)a)->code,((const struct Entry*)b)->code);
}
static void inventory_report(struct Inventory *inventory) {
qsort(inventory->entries,inventory->count,sizeof inventory->entries[0],compare);
bool first=true;
for(size_t i=0;i<inventory->count;++i) {
struct Entry *entry=&inventory->entries[i];
if(entry->stock.quantity>0) {
printf("%s%s:%lld",first?"":" ",entry->code,entry->stock.quantity);
first=false;
}
}
puts(first?"none":"");
}
int main(void) {
struct Inventory inventory={0};
char *line=NULL;int status;
while((status=read_line(&line,NULL))>0) {
char *code=strtok(line," \t\r\n\f\v");
if(code) {
char *amount=strtok(NULL," \t\r\n\f\v");
if(!amount){free(line);return EXIT_FAILURE;}
long long delta=strtoll(amount,NULL,10);
puts(inventory_change(&inventory,code,delta)?"true":"false");
}
free(line);
}
if(status<0)return EXIT_FAILURE;
inventory_report(&inventory);
for(size_t i=0;i<inventory.count;++i)free(inventory.entries[i].code);
return 0;
}
Try it yourself
require_relative 'exercise'
require_relative 'stock'
require_relative 'inventory'
def check(value)
raise 'Public API check failed' unless value
end
s = Stock.new
check(!s.change(-1) && s.quantity == 0 && s.change(4) && !s.change(-5) && s.quantity == 4)
i = Inventory.new
check(!i.change("x", -2) && i.report == "none")
check(i.change("b", 2) && i.change("a", 1) && i.report == "a:1 b:2")
puts solve(STDIN.read)
All lessons in Ruby for C 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