予約モジュールを移植する
Coddyの「Lua開発者のためのC」コースのレッスン 48/48。
チャレンジ
中級remaining フィールドを持つ Room 構造体と room_reserve(Room*,request) を使って、Lua の予約アルゴリズムを移植します。容量は 0 以上の整数で、リクエストは整数です。正の値で、残り容量内に収まるリクエストのみを受け入れ、true を返して remaining を減らします。拒否する場合は変更しません。入力は容量の後にリクエストが続きます。remaining:accepted を出力してください。ロックされた main は、2 つの部屋と更新の失敗を個別にテストします。これは構造体と関数のインターフェースであり、C のクラスではありません。
Lua の参照コード
local values={}
for word in io.read("a"):gmatch("%S+") do
values[#values+1]=tonumber(word)
end
local capacity=values[1]
local remaining=capacity
local accepted=0
for i=2,#values do
local request=values[i]
if request>0 and request<=remaining then
remaining=remaining-request
accepted=accepted+1
end
end
print(remaining..":"..accepted)ロックされていないソースファイルとヘッダーファイルを編集してください。表示されているロック済みの main.c が関数を直接呼び出すため、宣言されている公開 API との互換性を保ってください。別の main を追加しないでください。タスク内の数値は、範囲を明示的に検証するタスクを除き、オーバーフローが起きない程度に小さい値です。指定された出力のみを出力してください。ドライバーが示されている場合、入力の解析と出力はドライバーが行います。
自分で試してみよう
#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;}
Lua開発者のためのCのすべてのレッスン
自分で練習してみよう: Cオンラインコンパイラ