You are on page 1of 15

Railway reservation:

Main .java
import java.util.*;

public class Main


{

public static void bookTicket(Passenger p)


{
TicketBooker booker = new TicketBooker();

if(TicketBooker.availableWaitingList == 0)
{
System.out.println("No Tickets Available");
return;
}

if((p.berthPreference.equals("L") &&
TicketBooker.availableLowerBerths > 0 )||
(p.berthPreference.equals("M") &&
TicketBooker.availableMiddleBerths > 0) ||
(p.berthPreference.equals("U") &&
TicketBooker.availableUpperBerths > 0))
{
System.out.println("Preferred Berth Available");
if(p.berthPreference.equals("L"))
{
System.out.println("Lower Berth Given");

booker.bookTicket(p,(TicketBooker.lowerBerthsPositions.get(0)),"L");

TicketBooker.lowerBerthsPositions.remove(0);
TicketBooker.availableLowerBerths--;

}
else if(p.berthPreference.equals("M"))
{
System.out.println("Middle Berth Given");

booker.bookTicket(p,(TicketBooker.middleBerthsPositions.get(0)),"M");

TicketBooker.middleBerthsPositions.remove(0);
TicketBooker.availableMiddleBerths--;

}
else if(p.berthPreference.equals("U"))
{
System.out.println("Upper Berth Given");

booker.bookTicket(p,(TicketBooker.upperBerthsPositions.get(0)),"U");

TicketBooker.upperBerthsPositions.remove(0);
TicketBooker.availableUpperBerths--;
}
}

else if(TicketBooker.availableLowerBerths > 0)


{
System.out.println("Lower Berth Given");

booker.bookTicket(p,(TicketBooker.lowerBerthsPositions.get(0)),"L");

TicketBooker.lowerBerthsPositions.remove(0);
TicketBooker.availableLowerBerths--;

}
else if(TicketBooker.availableMiddleBerths > 0)
{
System.out.println("Middle Berth Given");

booker.bookTicket(p,(TicketBooker.middleBerthsPositions.get(0)),"M");

TicketBooker.middleBerthsPositions.remove(0);
TicketBooker.availableMiddleBerths--;

}
else if(TicketBooker.availableUpperBerths > 0)
{
System.out.println("Upper Berth Given");

booker.bookTicket(p,(TicketBooker.upperBerthsPositions.get(0)),"U");

TicketBooker.upperBerthsPositions.remove(0);
TicketBooker.availableUpperBerths--;

else if(TicketBooker.availableRacTickets > 0)


{
System.out.println("RAC available");
booker.addToRAC(p,(TicketBooker.racPositions.get(0)),"RAC" );
}

else if(TicketBooker.availableWaitingList > 0)


{
System.out.println("Added to Waiting List");

booker.addToWaitingList(p,(TicketBooker.waitingListPositions.get(0)),"WL");

public static void cancelTicket(int id)


{
TicketBooker booker = new TicketBooker();

if(!booker.passengers.containsKey(id))
{
System.out.println("Passenger detail Unknown");
}
else
booker.cancelTicket(id);
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
boolean loop = true;

while(loop)
{
System.out.println(" 1. Book Ticket \n 2. Cancel Ticket \n 3.
Available Tickets \n 4. Booked Tickets \n 5. Exit");
int choice = s.nextInt();
switch(choice)
{

case 1:
{

System.out.println("Enter Passenger name,age and berth


preference (L,M or U)");
String name = s.next();
int age = s.nextInt();

String berthPreference = s.next();

Passenger p = new Passenger(name,age,berthPreference);

bookTicket(p);
}
break;

case 2:
{

System.out.println("Enter passenger Id to cancel");


int id = s.nextInt();
cancelTicket(id);
}
break;

case 3:
{
TicketBooker booker = new TicketBooker();
booker.printAvailable();
}
break;

case 4:
{
TicketBooker booker = new TicketBooker();
booker.printPassengers();
}
break;

case 5:
{
loop = false;
}
break;
default:
break;
}
}
}
}

Passenger.java
public class Passenger
{
static int id = 1;
String name;
int age;
String berthPreference;
int passengerId;
String alloted;
int number;//seat number
public Passenger(String name,int age,String berthPreference)
{
this.name = name;
this.age = age;
this.berthPreference = berthPreference;
this.passengerId = id++;
alloted = "";
number = -1;
}
}

TicketBooker.java
import java.util.*;
public class TicketBooker
{

static int availableLowerBerths = 1;


static int availableMiddleBerths = 1;
static int availableUpperBerths = 1;
static int availableRacTickets = 1;
static int availableWaitingList = 1;0

static Queue<Integer> waitingList = new LinkedList<>();


static Queue<Integer> racList = new LinkedList<>();
static List<Integer> bookedTicketList = new ArrayList<>();

static List<Integer> lowerBerthsPositions = new


ArrayList<>(Arrays.asList(1));
static List<Integer> middleBerthsPositions = new
ArrayList<>(Arrays.asList(1));
static List<Integer> upperBerthsPositions = new
ArrayList<>(Arrays.asList(1));
static List<Integer> racPositions = new ArrayList<>(Arrays.asList(1));
static List<Integer> waitingListPositions = new
ArrayList<>(Arrays.asList(1));

static Map<Integer, Passenger> passengers = new HashMap<>();

//book ticket
public void bookTicket(Passenger p, int berthInfo,String allotedBerth)
{

p.number = berthInfo;
p.alloted = allotedBerth;

passengers.put(p.passengerId,p);

bookedTicketList.add(p.passengerId);
System.out.println("--------------------------Booked
Successfully");
}

public void addToRAC(Passenger p,int racInfo,String allotedRAC)


{

p.number = racInfo;
p.alloted = allotedRAC;

passengers.put(p.passengerId,p);

racList.add(p.passengerId);

availableRacTickets--;

racPositions.remove(0);

System.out.println("--------------------------added to RAC
Successfully");
}

public void addToWaitingList(Passenger p,int waitingListInfo,String


allotedWL)
{
p.number = waitingListInfo;
p.alloted = allotedWL;

passengers.put(p.passengerId,p);

waitingList.add(p.passengerId);

availableWaitingList--;

waitingListPositions.remove(0);

System.out.println("-------------------------- added to Waiting


List Successfully");
}

//cancel ticket
public void cancelTicket(int passengerId)
{

Passenger p = passengers.get(passengerId);
passengers.remove(Integer.valueOf(passengerId));

bookedTicketList.remove(Integer.valueOf(passengerId));

int positionBooked = p.number;


System.out.println("---------------cancelled Successfully");

if(p.alloted.equals("L"))
{
availableLowerBerths++;
lowerBerthsPositions.add(positionBooked);
}
else if(p.alloted.equals("M"))
{
availableMiddleBerths++;
middleBerthsPositions.add(positionBooked);
}
else if(p.alloted.equals("U"))
{
availableUpperBerths++;
upperBerthsPositions.add(positionBooked);
}

//check if any RAC is there


if(racList.size() > 0)
{
Passenger passengerFromRAC = passengers.get(racList.poll());
int positionRac = passengerFromRAC.number;
racPositions.add(positionRac);
racList.remove(Integer.valueOf(passengerFromRAC.passengerId));
availableRacTickets++;

//check if any WL is there


if(waitingList.size()>0)
{

Passenger passengerFromWaitingList =
passengers.get(waitingList.poll());
int positionWL = passengerFromWaitingList.number;
waitingListPositions.add(positionWL);

waitingList.remove(Integer.valueOf(passengerFromWaitingList.passengerId));

passengerFromWaitingList.number = racPositions.get(0);
passengerFromWaitingList.alloted = "RAC";
racPositions.remove(0);
racList.add(passengerFromWaitingList.passengerId);

availableWaitingList++;
availableRacTickets--;
}

Main.bookTicket(passengerFromRAC);
}

public void printAvailable()


{
System.out.println("Available Lower Berths " +
availableLowerBerths);
System.out.println("Available Middle Berths " +
availableMiddleBerths);
System.out.println("Available Upper Berths " +
availableUpperBerths);
System.out.println("Availabel RACs " + availableRacTickets);
System.out.println("Available Waiting List " +
availableWaitingList);
System.out.println("--------------------------");
}

public void printPassengers()


{
if(passengers.size() == 0)
{
System.out.println("No details of passengers");
return;
}
for(Passenger p : passengers.values())
{
System.out.println("PASSENGER ID " + p.passengerId );
System.out.println(" Name " + p.name );
System.out.println(" Age " + p.age );
System.out.println(" Status " + p.number + p.alloted);
System.out.println("--------------------------");
}
}
}

TAXI BOOKING:

Taxi.java

import java.util.*;

public class Taxi

static int taxicount = 0; // taxi number

int id;

boolean booked; //taxi booked or not

char currentSpot; //where taxi is now

int freeTime; // when taxi becomes free

int totalEarnings; // total earnings of taxi

List<String> trips; // all details of all trips by this taxi


public Taxi()

booked = false;

currentSpot = 'A';//start point A

freeTime = 6;//example 6 AM

totalEarnings = 0;

trips = new ArrayList<String>();

taxicount = taxicount + 1; // everytime new taxi is created a new id will be assigned

id = taxicount;

public void setDetails(boolean booked,char currentSpot,int freeTime,int totalEarnings,String


tripDetail)

this.booked = booked;

this.currentSpot = currentSpot;

this.freeTime = freeTime;

this.totalEarnings = totalEarnings;

this.trips.add(tripDetail);

public void printDetails()

//print all trips details

System.out.println("Taxi - "+ this.id + " Total Earnings - " + this.totalEarnings);

System.out.println("TaxiID BookingID CustomerID From To PickupTime DropTime


Amount");

for(String trip : trips)

System.out.println(id + " " + trip);

System.out.println("--------------------------------------------------------------------------------------");
}

public void printTaxiDetails()

//print total earningand taxi details like current location and free time

System.out.println("Taxi - "+ this.id + " Total Earnings - " + this.totalEarnings + " Current spot - "
+ this.currentSpot +" Free Time - " + this.freeTime);

Booking.java

/*

The are 6 points(A,B,C,D,E,F) 15 KM apart 60 min travel between each, n taxis all taxis at A starting

100 rs for first 5 KM and then 10 for each of the further KMs, rate from pickup to drop only

pickup time example : 9 hrs, 15 hrs

When a customer books a Taxi, a free taxi at that point is allocated

-If no free taxi is available at that point, a free taxi at the nearest point is allocated.

-If two taxi’s are free at the same point, one with lower earning is allocated

-If no taxi is free at that time, booking is rejected

Input 1:

Customer ID: 1

Pickup Point: A

Drop Point: B

Pickup Time: 9

Output 1:
Taxi can be allotted.

Taxi-1 is allotted

*/

import java.util.*;

public class Booking

public static void bookTaxi(int customerID,char pickupPoint,char dropPoint,int


pickupTime,List<Taxi> freeTaxis)

// to find nearest

int min = 999;

//distance between pickup and drop

int distanceBetweenpickUpandDrop = 0;

//this trip earning

int earning = 0;

//when taxi will be free next

int nextfreeTime = 0;

//where taxi is after trip is over

char nextSpot = 'Z';

//booked taxi

Taxi bookedTaxi = null;

//all details of current trip as string

String tripDetail = "";


for(Taxi t : freeTaxis)

int distanceBetweenCustomerAndTaxi = Math.abs((t.currentSpot - '0') - (pickupPoint - '0')) *


15;

if(distanceBetweenCustomerAndTaxi < min)

bookedTaxi = t;

//distance between pickup and drop = (drop - pickup) * 15KM

distanceBetweenpickUpandDrop = Math.abs((dropPoint - '0') - (pickupPoint - '0')) * 15;

//trip earning = 100 + (distanceBetweenpickUpandDrop-5) * 10

earning = (distanceBetweenpickUpandDrop-5) * 10 + 100;

//drop time calculation

int dropTime = pickupTime + distanceBetweenpickUpandDrop/15;

//when taxi will be free next

nextfreeTime = dropTime;

//taxi will be at drop point after trip

nextSpot = dropPoint;

// creating trip detail

tripDetail = customerID + " " + customerID + " " + pickupPoint + " "+
dropPoint + " " + pickupTime + " " +dropTime + " " + earning;

min = distanceBetweenCustomerAndTaxi;

//setting corresponding details to allotted taxi

bookedTaxi.setDetails(true,nextSpot,nextfreeTime,bookedTaxi.totalEarnings +
earning,tripDetail);
//BOOKED SUCCESSFULLY

System.out.println("Taxi " + bookedTaxi.id + " booked");

public static List<Taxi> createTaxis(int n)

List<Taxi> taxis = new ArrayList<Taxi>();

// create taxis

for(int i=1 ;i <=n;i++)

Taxi t = new Taxi();

taxis.add(t);

return taxis;

public static List<Taxi> getFreeTaxis(List<Taxi> taxis,int pickupTime,char pickupPoint)

List<Taxi> freeTaxis = new ArrayList<Taxi>();

for(Taxi t : taxis)

//taxi should be free

//taxi should have enough time to reach customer before pickuptime

if(t.freeTime <= pickupTime && (Math.abs((t.currentSpot - '0') - (pickupPoint - '0')) <=


pickupTime - t.freeTime))

freeTaxis.add(t);

return freeTaxis;

}
public static void main(String[] args)

//create 4 taxis

List<Taxi> taxis = createTaxis(4);

Scanner s = new Scanner(System.in);

int id = 1;

while(true)

System.out.println("0 - > Book Taxi");

System.out.println("1 - > Print Taxi details");

int choice = s.nextInt();

switch(choice)

case 0:

//get details from customers

int customerID = id;

System.out.println("Enter Pickup point");

char pickupPoint = s.next().charAt(0);

System.out.println("Enter Drop point");

char dropPoint = s.next().charAt(0);

System.out.println("Enter Pickup time");

int pickupTime = s.nextInt();

//check if pickup and drop points are valid


if(pickupPoint < 'A' || dropPoint > 'F' || pickupPoint > 'F' || dropPoint < 'A')

System.out.println("Valid pickup and drop are A, B, C, D, E, F. Exitting");

return;

// get all free taxis that can reach customer on or before pickup time

List<Taxi> freeTaxis = getFreeTaxis(taxis,pickupTime,pickupPoint);

//no free taxi means we cannot allot, exit!

if(freeTaxis.size() == 0)

System.out.println("No Taxi can be alloted. Exitting");

return;

//sort taxis based on earnings

Collections.sort(freeTaxis,(a,b)->a.totalEarnings - b.totalEarnings);

// 3,4,2 - > 2,3,4

//get free Taxi nearest to us

bookTaxi(id,pickupPoint,dropPoint,pickupTime,freeTaxis);

id++;

break;

case 1:

//two functions to print details

for(Taxi t : taxis)

t.printTaxiDetails();

for(Taxi t : taxis)

t.printDetails();
break;

default:

return;

You might also like