Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Problem : Given two types of cars (S/L) and a parking with two type of parking spots (S/L) write a class with two fuctions parkCar(Car) that will return the locaiton of the parked car and fetechCar(loc) that returns
- the car parked in that location;
- class Car{
- int plateNo;
- boolean isLarge;
- public Car(int plateNo, boolean isLarge){
- this.palteNo = plate;
- this.isLarge = isLarge;
- }
- }
- class Spot{
- int loc;
- boolean isLarge;
- Car car;
- public Spot(int loc, boolean isLarge){
- this.isLarge = isLarge;
- this.loc = loc;
- this.car = null;
- }
- }
- class Parking{
- Stack<Spot> smallSpots;
- Stack<Spot> largeSpots;
- Map<Integer, Spot> taken;
- public Parking(){
- smallSpots = new Stack<Spots>();
- largeSpots = new Stack<Spots>();
- taken = new HashMap<Integer, Spot>();
- }
- public int parkCar(Car car){
- Spot parkingSpot = null;
- int location = -1;
- if(car.isLarge && largeSpots.size()!=0){
- parkingSpot = largeSpots.pop();
- }else if(!car.isLarge && (largeSpots.size()!=0 || smallSpots.size()!=0)){ // he wanted to make these if checks smaller or simpler said my code works but its complicated
- parkingSpot = smallSpots.size()!=0?smallSpots.pop():largeSpots.pop();
- }
- if(parkingSpot==null){
- Sysout("Parking full, cant park");
- return location;
- }
- parkingSpot.car = car; // ispe ro rha tha banda ki direct access kar loge, So I made a getter setter afterwards
- location = parkingSpot.loc; // pehle ye line bhi if mai likhi thi maine bad mai jab usne simple karne ko bola toh niche likh di
- taken.put(location, parkingSpot);
- return location;
- }
- public Car fetchCar(int n){
- if(taken.containsKey(n)){
- Spot parkingSpot = taken.get(n);
- Car fetechedCar = parkingSpot.car;
- parkingSpot.car = null;
- if(parkingSpot.isLarge){
- largeSpots.push(parkingSpot);
- }else{
- smallSpots.push(parkingSpot);
- }
- taken.remove(n);
- return fetechedCar;
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement