CSharp · Console
// Write a hotel management program with given interface.
// Each method (except constructor) should take fixed time (not dependent on hotel size).
using System;
using System.Diagnostics;
public class Program
{
public static void Main(string[] args)
{
Hotel hotel = new Hotel(5);
// test sequence: 0 means check-in, >0 means check-out
foreach(int room in new int[]{ 0,0,0,0,0,4,2,0,0})
Test(hotel, room);
}
public static void Test(Hotel hotel, int n)
{
if(n == 0)
{ // test check in
Console.WriteLine("Room {0} allocated", hotel.checkIn());
}
else
{ // test check out
hotel.checkOut(n);
Console.WriteLine("Room {0} freed", n);
}
}
}
public class Hotel
{
Queue freeRooms;
// constructor to set number of rooms
public Hotel(int totalNumberOfRooms)
{
freeRooms = new Queue(totalNumberOfRooms);
for (int i = 1; i <= totalNumberOfRooms; i++)
freeRooms.Push(i);
}
public bool hasRoomsAvailable()
{
return !freeRooms.IsEmpty();
}
// Before: hasRoomsAvailable
public int checkIn()
{
Trace.Assert(hasRoomsAvailable());
return freeRooms.Pop();
}
// Before: roomNumber is occupied
public void checkOut(int roomNumber)
{
freeRooms.Push(roomNumber);
}
}
public class Queue
{
// invariant:
// the array is considered as circular (next index after data.Length-1 is 0)
// the queue contains count elements residing in data[head], data[head+1] etc
private int[] data;
private int head = 0;
private int count = 0;
public Queue(int size)
{
data = new int[size];
}
public bool IsEmpty()
{
return count == 0;
}
public bool IsFull()
{
return count == data.Length;
}
public void Push(int v)
{
if (IsFull())
throw new ApplicationException("Queue full");
data[(head + count) % data.Length] = v;
count++;
}
public int Pop()
{
if (IsEmpty())
throw new ApplicationException("Queue empty");
int v = data[head];
head = (head + 1) % data.Length;
count--;
return v;
}
}