Menu
CoddyTech

Chuyển đổi đối tượng phòng từ C#

Bài học 48 trên 48 trong khóa học Lua dành cho lập trình viên C# của Coddy.

challenge icon

Thử thách

Trung bình

Chuyển bản tham chiếu C#. Dòng đầu tiên của đầu vào là sức chứa phòng không âm; các dòng còn lại là yêu cầu đặt chỗ bằng số nguyên có dấu. Chỉ chấp nhận yêu cầu lớn hơn 0 và vừa với sức chứa. Yêu cầu thất bại không làm thay đổi số ghế đã sử dụng. Trả về remaining:accepted. Triển khai Model.new(capacity) và Model:reserve(seats) trong model.lua; reserve trả về một giá trị boolean. Dùng một đối tượng mới cho mỗi lần chạy.

Bản tham chiếu C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
string first=Console.ReadLine();
var room=new Room(long.Parse(first,System.Globalization.CultureInfo.InvariantCulture));
long accepted=0;
string line;
while((line=Console.ReadLine())!=null){
    if(room.Reserve(long.Parse(line,System.Globalization.CultureInfo.InvariantCulture))) accepted++;
}
Console.WriteLine((room.Capacity-room.Used).ToString(System.Globalization.CultureInfo.InvariantCulture)+":"+accepted.ToString(System.Globalization.CultureInfo.InvariantCulture));
class Room {
    public long Capacity {get;}
    public long Used {get;private set;}
    public Room(long capacity){Capacity=capacity;}
    public bool Reserve(long seats){
        if(seats<=0 || seats>Capacity-Used) return false;
        Used+=seats;
        return true;
    }
}

Chỉnh sửa app.lua, model.lua. Tệp main.lua bị khóa và hiển thị sẽ đọc stdin thành một chuỗi dòng, gọi app.run(lines) và in giá trị trả về kèm theo một ký tự xuống dòng ở cuối. Không in thông tin chẩn đoán hoặc thay đổi tên module. Đầu vào rỗng tạo thành một chuỗi rỗng. Mọi đầu vào số đều đủ nhỏ để tránh tràn số.

Kiểm tra API công khai: Model.new(capacity) cung cấp capacity và used, ban đầu bằng không. reserve trả về một giá trị boolean và chỉ cập nhật used khi yêu cầu lớn hơn 0 và vừa với sức chứa. Các phòng độc lập với nhau. Trình điều khiển bị khóa kiểm tra hành vi này trước khi gọi app.run. Các kiểm tra này không in gì khi thành công.

Tự làm thử

-- Kiểm tra API công khai
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))

Tất cả bài học trong Lua dành cho lập trình viên C#

Tự luyện tập: Trình biên dịch Lua online