Port a Reservation Module
Lesson 48 of 48 in Coddy's C for Go Developers course.
Challenge
MediumPort the Go reservation algorithm using a Room struct with remaining field and room_reserve(Room*,request). Capacity is a nonnegative integer; requests are integers. Accept only positive affordable requests, returning true and decrementing remaining. Reject without mutation. Input is capacity followed by requests; print remaining:accepted. The locked main independently probes two rooms and failed updates. This is a struct-and-functions interface, not a C class.
Edit the unlocked source and header files. Keep the declared public API compatible with the visible locked main.c, which calls it directly. Do not add another main. All numeric task fixtures are small enough to avoid overflow unless the task explicitly checks a range. Print only the specified output; the driver supplies input parsing and output when shown.
Go reference
package main
import("fmt";"os";"bufio")
type Room struct{Remaining int}
func(r *Room)Reserve(n int)bool{if n<=0||n>r.Remaining{return false};r.Remaining-=n;return true}
func main(){in:=bufio.NewReader(os.Stdin);r:=Room{};fmt.Fscan(in,&r.Remaining);accepted:=0;for{var n int;if _,err:=fmt.Fscan(in,&n);err!=nil{break};if r.Reserve(n){accepted++}};fmt.Printf("%d:%d\n",r.Remaining,accepted)}
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){Room a={3},b={5};if(room_reserve(&a,0)||room_reserve(&a,-1)||room_reserve(&a,4)||a.remaining!=3||!room_reserve(&a,2)||a.remaining!=1||b.remaining!=5)return 3;Room room;if(scanf("%d",&room.remaining)!=1)return 1;int request,accepted=0;while(scanf("%d",&request)==1)if(room_reserve(&room,request))accepted++;printf("%d:%d\n",room.remaining,accepted);return 0;}
All lessons in C for Go Developers
1Compile and Compute
Run C Across FilesPrinting and CommentsTypes and InitializationInteger Division and RangeFloating ArithmeticRecap: Receipt Total4Functions and Interfaces
Function Arguments Are ValuesHeaders and LinkageMultiple Results via PointersConst Views and MutationRecap: Price Breakdown2Decisions and Loops
Booleans and BranchesLogical OperatorsSwitch and Enumerated CasesLoop Bounds and ProgressRecap: Admission RulesPractice on your own: Online C compiler