BUS SEAT RESERVATION
/*Write a program to reserve the specified number of seats contiguously as
* far as possible, if not able to reserve the seats contiguously, then reserve
* the available seats.
*/
{
class SeatsRow
{
public Boolean[] Seats = null;
public int RemainningSeats { get; set; }
public SeatsRow(int No_Seats)
{
Seats = new Boolean[No_Seats];
RemainningSeats = No_Seats;
for (int i = 0; i < Seats.Length; i++)
{
Seats[i] = false;
}
}
public int Reserve(int numberOfSeats)
{
if (numberOfSeats <= 0) return 0;
int count = 0;
for(int i=0;i<Seats.Length;i++)
{
if (Seats[i] == false)
{
Seats[i] = true;
count++;
}
if (count == numberOfSeats) break;
}
RemainningSeats -= count;
return count;
}
public void Print()
{
for(int i=0;i<Seats.Length;i++)
{
Console.Write(Seats[i] == true ? "T" : "F");
}
}
}
class Bus
{
SeatsRow[] seatRows = null;
public Bus(int rows, int numberOfSeats)
{
seatRows = new SeatsRow[rows];
for (int i = 0; i < seatRows.Length; i++)
{
seatRows[i] = new SeatsRow(numberOfSeats);
}
}
public int Reserve(int numberOfSeats)
{
int numberOfSeatsToReserve = numberOfSeats;
for (int i = 0; i < seatRows.Length; i++)
{
if (seatRows[i].RemainningSeats >= numberOfSeatsToReserve)
{
numberOfSeatsToReserve -= seatRows[i].Reserve(numberOfSeatsToReserve);
}
}
if (numberOfSeatsToReserve == 0)
{
foreach (SeatsRow r in seatRows)
{
r.Print();
Console.WriteLine();
}
return numberOfSeats;
}
for (int i = 0; i < seatRows.Length ; i++)
{
numberOfSeatsToReserve -= seatRows[i].Reserve(numberOfSeatsToReserve);
}
foreach (SeatsRow r in seatRows)
{
r.Print();
Console.WriteLine();
}
return numberOfSeats - numberOfSeatsToReserve;
}
}
class Program
{
static void Main(string[] args)
{
Bus b = new Bus(4, 4);
b.Reserve(5);
Console.WriteLine();
b.Reserve(3);
Console.WriteLine();
b.Reserve(3);
Console.WriteLine();
b.Reserve(3);
Console.WriteLine();
b.Reserve(4);
Console.WriteLine();
}
}
}
No comments:
Post a Comment