forked from super30admin/Design-5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParkingLot.java
96 lines (78 loc) · 2.65 KB
/
ParkingLot.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// "static void main" must be defined in a public class.
public class Main {
public static class Spot {
public int spotId;
public int floorNo;
public Spot(int spotId, int floorNo){
this.spotId = spotId;
this.floorNo = floorNo;
}
}
public static class ParkingLot {
PriorityQueue<Spot> pq;
public int spotsPerFloor;
public int maxFloors;
public ParkingLot (int spotId, int maxFloors){
this.spotsPerFloor = spotsPerFloor;
this.maxFloors = maxFloors;
pq = new PriorityQueue<>((a,b) -> {
if(b.floorNo == a.floorNo){
return a.spotId - b.spotId;
}
return a.floorNo - b.floorNo;
});
}
Spot getNextAvailableSpot(){
if(!pq.isEmpty()){
return pq.peek();
}
return null;
}
Spot park(){
if(!pq.isEmpty()){
return pq.poll();
}
return null;
}
void unpark(int spotId, int floorNo){
addParkingSpot(spotId, floorNo);
}
void addParkingSpot(int spotId, int floorNo){
if(floorNo <=0 && floorNo > maxFloors){
throw new IllegalArgumentException("Floor No is invalid");
}
if(spotId <=0 && spotId > spotsPerFloor){
throw new IllegalArgumentException("Spot No is invalid");
}
pq.add(new Spot(spotId, floorNo));
}
}
public static void main(String[] args) {
ParkingLot lot = new ParkingLot(10, 20);
lot.addParkingSpot(1,1);
lot.addParkingSpot(2,1);
lot.addParkingSpot(1,2);
lot.addParkingSpot(2,2);
lot.addParkingSpot(1,3);
lot.addParkingSpot(1,4);
printNextAvailableSpot(lot);
lot.park(); // 1,1
lot.park(); // 2,1
lot.park(); // 1,2
printNextAvailableSpot(lot); // 2,2
lot.unpark(1,1);
printNextAvailableSpot(lot); // 1,1
}
private static void printNextAvailableSpot(ParkingLot lot) {
Spot nextSpot = lot.getNextAvailableSpot();
if(nextSpot != null){
System.out.printf("Next available spot %d | floor %d\n",nextSpot.spotId, nextSpot.floorNo);
}
}
/*
OUTPUT :
Next available spot 1 | floor 1
Next available spot 2 | floor 2
Next available spot 1 | floor 1
*/
}