-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem2_FlashSaleInventoryManager.java
More file actions
53 lines (39 loc) · 1.63 KB
/
Problem2_FlashSaleInventoryManager.java
File metadata and controls
53 lines (39 loc) · 1.63 KB
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
import java.util.*;
class InventoryManager {
HashMap<String, Integer> stock = new HashMap<String, Integer>();
HashMap<String, LinkedList<Integer>> waitingList = new HashMap<String, LinkedList<Integer>>();
public InventoryManager() {
stock.put("IPHONE15_256GB", 100);
waitingList.put("IPHONE15_256GB", new LinkedList<Integer>());
}
public int checkStock(String productId) {
if (stock.containsKey(productId)) {
return stock.get(productId);
}
return 0;
}
public synchronized String purchaseItem(String productId, int userId) {
int currentStock = stock.get(productId);
if (currentStock > 0) {
stock.put(productId, currentStock - 1);
return "Success, " + (currentStock - 1) + " units remaining";
} else {
LinkedList<Integer> queue = waitingList.get(productId);
queue.add(userId);
int position = queue.size();
return "Added to waiting list, position #" + position;
}
}
}
public class Problem2_FlashSaleInventoryManager {
public static void main(String[] args) {
InventoryManager manager = new InventoryManager();
System.out.println("Stock: " + manager.checkStock("IPHONE15_256GB") + " units available");
System.out.println(manager.purchaseItem("IPHONE15_256GB", 12345));
System.out.println(manager.purchaseItem("IPHONE15_256GB", 67890));
for (int i = 0; i < 100; i++) {
manager.purchaseItem("IPHONE15_256GB", 20000 + i);
}
System.out.println(manager.purchaseItem("IPHONE15_256GB", 99999));
}
}