Menu
CoddyTech

انقل كائنات الغرفة

الدرس 48 من 48 في دورة Luau لمطوّري Go على Coddy.

challenge icon

التحدي

متوسط

انقل التنفيذ المرجعي المكتوب بلغة Go. سطر الإدخال الأول هو سعة الغرفة غير السالبة؛ أما الأسطر المتبقية فهي طلبات حجز بأعداد صحيحة موقّعة. اقبل الطلبات الموجبة فقط إذا كانت تتسع. الطلبات المرفوضة لا تغيّر عدد المقاعد المستخدمة. أعد remaining:accepted. نفّذ Model.new(capacity) وModel:reserve(seats) في model.luau؛ وتُعيد reserve قيمة منطقية. استخدم كائنًا جديدًا في كل تشغيل.

التنفيذ المرجعي بلغة Go

package main
import("fmt";"io";"os";"strconv";"strings")
type Room struct {Capacity,Used int64}
func(r *Room) Reserve(seats int64)bool {
 if seats<=0 || seats>r.Capacity-r.Used {return false}
 r.Used+=seats
 return true
}
func main(){
 raw,err:=io.ReadAll(os.Stdin); if err!=nil {panic(err)}
 lines:=strings.Fields(string(raw))
 capacity,err:=strconv.ParseInt(lines[0],10,64); if err!=nil {panic(err)}
 room:=Room{Capacity:capacity}; accepted:=0
 for _,line:=range lines[1:] {seats,err:=strconv.ParseInt(line,10,64); if err!=nil {panic(err)}; if room.Reserve(seats){accepted++}}
 fmt.Printf("%d:%d\n",room.Capacity-room.Used,accepted)
}

عدّل app.luau وmodel.luau. يقرأ main.luau المقفل والظاهر بيانات stdin في تسلسل من الأسطر، ويستدعي app.run(lines)، ويطبع القيمة التي تُعيدها مع سطر جديد أخير. لا تطبع رسائل تشخيصية ولا تغيّر أسماء الوحدات. الإدخال الفارغ يعطي تسلسلًا فارغًا. جميع المدخلات الرقمية صغيرة بما يكفي لتجنّب تجاوز السعة.

فحوصات الواجهة البرمجية العامة: يوفّر Model.new(capacity) الخاصيتين capacity وused، وتكون قيمة used صفرًا في البداية. تُعيد reserve قيمة منطقية، ولا تحدّث used إلا عند تقديم طلب موجب يتسع. الغرف مستقلة عن بعضها. يتحقق المشغّل المقفل من هذا السلوك قبل استدعاء app.run. لا تطبع هذه الفحوصات شيئًا عند نجاحها.

جرّب بنفسك

-- فحوصات واجهة البرمجة العامة
do
local Model=require("./model")
local a,b=Model.new(5),Model.new(2)
assert(a:reserve(6)==false and a.used==0,"oversized reservation must not mutate")
assert(a:reserve(0)==false and a:reserve(-1)==false and a.used==0,"nonpositive requests are rejected")
assert(a:reserve(2)==true and a.used==2,"accepted seats update used")
assert(a:reserve(3)==true and a.used==5 and a.capacity==5,"exact fit succeeds without changing capacity")
assert(b.used==0 and b.capacity==2,"rooms must be independent")
end
local app = require("./app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))

جميع دروس Luau لمطوّري Go

تدرّب بنفسك: مترجم Luau عبر الإنترنت