-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRationDistributionSystem.java
More file actions
679 lines (614 loc) · 19.5 KB
/
Copy pathRationDistributionSystem.java
File metadata and controls
679 lines (614 loc) · 19.5 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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
import java.util.*;
//ABSTRACTION
abstract class Person
{
private String name;
private int age;
private String phoneNumber;
public Person(String name, int age, String phoneNumber)
{
this.name = name;
this.age = age;
this.phoneNumber = phoneNumber;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String getPhoneNumber()
{
return phoneNumber;
}
public abstract void displayDetails();
}
// CUSTOMER
class Customer extends Person
{
private String rationCardId;
private String category; // Antyodaya | BPL | APL
private String area;
private String state;
public Customer(String name, int age, String phoneNumber, String rationCardId, String category, String area, String state)
{
super(name, age, phoneNumber);
this.rationCardId = rationCardId;
this.category = category;
this.area = area;
this.state = state;
}
public String getRationCardId()
{
return rationCardId;
}
public String getCategory()
{
return category;
}
public String getArea()
{
return area;
}
public String getState()
{
return state;
}
@Override
public void displayDetails()
{
System.out.println("Customer: " + getName() +
" | Age: " + getAge() +
" | Card: " + rationCardId +
" | Category: " + category +
" | Area: " + area +
" | State: " + state);
}
}
// INVENTORY (Array element)
class Inventory
{
private String itemName;
private int quantity;
private double pricePerKg;
private int threshold;
public Inventory(String itemName, int quantity, double pricePerKg, int threshold)
{
this.itemName = itemName;
this.quantity = quantity;
this.pricePerKg = pricePerKg;
this.threshold = threshold;
}
public String getItemName()
{
return itemName;
}
public int getQuantity()
{
return quantity;
}
public double getPricePerKg()
{
return pricePerKg;
}
public int getThreshold()
{
return threshold;
}
public boolean isBelowThreshold()
{
return quantity < threshold;
}
public void reduceStock(int qty)
{
if (qty <= quantity) quantity -= qty;
else System.out.println("Not enough stock for " + itemName);
}
public void addStock(int qty)
{
quantity += qty;
}
public void display()
{
System.out.printf("%-12s | Stock: %4d kg | Rs.%.1f/kg | Threshold: %d kg%n",
itemName, quantity, pricePerKg, threshold);
}
}
// SHOP (DSA: STATIC ARRAY)
class Shop
{
private String shopId;
private String shopName;
private String location;
private String state;
private Inventory[] stock; // STATIC ARRAY — fixed-size inventory
private int stockCount;
private Map<String, Integer> allocationRates;
public Shop(String shopId, String shopName, String location, String state, int capacity)
{
this.shopId = shopId;
this.shopName = shopName;
this.location = location;
this.state = state;
this.stock = new Inventory[capacity];
this.stockCount = 0;
this.allocationRates = new HashMap<>();
initializeRegionalAllocation();
}
// Regional dietary requirements
private void initializeRegionalAllocation()
{
switch (state)
{
case "Punjab":
case "Haryana":
allocationRates.put("Rice", 5);
allocationRates.put("Wheat", 10);
allocationRates.put("Sugar", 2);
allocationRates.put("Oil", 1);
break;
case "West Bengal":
allocationRates.put("Rice", 10);
allocationRates.put("Wheat", 3);
allocationRates.put("Sugar", 2);
allocationRates.put("Oil", 1);
break;
case "Kerala":
allocationRates.put("Rice", 8);
allocationRates.put("Wheat", 4);
allocationRates.put("Sugar", 2);
allocationRates.put("Oil", 1);
break;
default:
allocationRates.put("Rice", 6);
allocationRates.put("Wheat", 6);
allocationRates.put("Sugar", 2);
allocationRates.put("Oil", 1);
}
}
// Array insertion
public void addItem(Inventory item)
{
if (stockCount < stock.length)
stock[stockCount++] = item;
}
// Array traversal
public void displayStock()
{
System.out.println("\n--- Stock at " + shopName + " (" + location + ", " + state + ") ---");
for (int i = 0; i < stockCount; i++) stock[i].display();
}
// Linear search in array
public Inventory searchItem(String itemName)
{
for (int i = 0; i < stockCount; i++)
if (stock[i].getItemName().equalsIgnoreCase(itemName))
return stock[i];
return null;
}
// Allocation per category (mirrors UI logic)
public int getAllocation(String itemName, String category)
{
int base = allocationRates.getOrDefault(itemName, 5);
if (category.equalsIgnoreCase("Antyodaya")) return base;
if (category.equalsIgnoreCase("BPL")) return base * 2 / 3;
return base / 2;
}
public Inventory[] getAllStock()
{
return stock;
}
public int getStockCount()
{
return stockCount;
}
public String getState()
{
return state;
}
}
// LINKED LIST (DSA: SINGLY LINKED LIST)
class Node
{
Customer data;
Node next;
Node(Customer data)
{
this.data = data;
}
}
class BeneficiaryList
{
private Node head;
// Insert at end — O(n)
public void addBeneficiary(Customer c)
{
Node newNode = new Node(c);
if (head == null)
{
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) temp = temp.next;
temp.next = newNode;
}
// Insert at beginning — O(1)
public void addAtBeginning(Customer c)
{
Node newNode = new Node(c);
newNode.next = head;
head = newNode;
}
// Linear search — O(n)
public Customer searchByCard(String cardId)
{
Node temp = head;
while (temp != null)
{
if (temp.data.getRationCardId().equalsIgnoreCase(cardId))
return temp.data;
temp = temp.next;
}
return null;
}
// Delete node by card ID
public boolean deleteBeneficiary(String cardId)
{
if (head == null) return false;
if (head.data.getRationCardId().equalsIgnoreCase(cardId))
{
head = head.next;
return true;
}
Node temp = head;
while (temp.next != null &&
!temp.next.data.getRationCardId().equalsIgnoreCase(cardId))
temp = temp.next;
if (temp.next != null)
{
temp.next = temp.next.next;
return true;
}
return false;
}
// Convert to array (needed for sorting)
public Customer[] toArray()
{
int count = 0;
Node t = head;
while (t != null)
{
count++;
t = t.next;
}
Customer[] arr = new Customer[count];
t = head;
for (int i = 0; i < count; i++)
{
arr[i] = t.data;
t = t.next;
}
return arr;
}
public void displayAll()
{
System.out.println("\n All Beneficiaries (Linked List)");
Node temp = head;
if (temp == null)
{
System.out.println("No records.");
return;
}
while (temp != null)
{
temp.data.displayDetails();
temp = temp.next;
}
}
public int size()
{
int count = 0;
Node temp = head;
while (temp != null)
{
count++;
temp = temp.next;
}
return count;
}
}
//QUEUE + STACK (DSA: FIFO Queue & LIFO Stack)
class DistributionQueue
{
private LinkedList<Customer> queue = new LinkedList<>(); // FIFO
private Stack<Customer> completedStack = new Stack<>(); // LIFO
// Enqueue — insert at rear
public void enqueue(Customer c)
{
queue.addLast(c);
System.out.println(c.getName() + " added to distribution queue.");
}
// Dequeue — remove from front, push to completed stack
public Customer dequeue()
{
if (queue.isEmpty())
{
System.out.println("Queue is empty.");
return null;
}
Customer served = queue.removeFirst();
completedStack.push(served); // PUSH to stack
return served;
}
public boolean isEmpty()
{
return queue.isEmpty();
}
public Customer peek()
{
return queue.isEmpty() ? null : queue.getFirst();
}
public boolean isInQueue(String cardId)
{
for (Customer c : queue)
if (c.getRationCardId().equalsIgnoreCase(cardId)) return true;
return false;
}
public String getStatus(String cardId)
{
if (isInQueue(cardId)) return "PENDING";
for (Customer c : completedStack)
if (c.getRationCardId().equalsIgnoreCase(cardId)) return "COMPLETED";
return "NOT FOUND";
}
public int queueSize()
{
return queue.size();
}
public LinkedList<Customer> getQueue()
{
return queue;
}
public Stack<Customer> getCompletedStack()
{
return completedStack;
}
public void displayQueue()
{
System.out.println("\nDistribution Queue (FIFO) ");
if (queue.isEmpty())
{
System.out.println("Queue is empty.");
return;
}
int pos = 1;
for (Customer c : queue)
System.out.println(pos++ + ". " + c.getName() + " [" + c.getRationCardId() + "]");
}
}
// SORTING (DSA: BUBBLE SORT & INSERTION SORT)
class SortBeneficiaries
{
// Bubble Sort by area — O(n²)
public static void sortByArea(Customer[] arr)
{
int n = arr.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j].getArea().compareToIgnoreCase(arr[j+1].getArea()) > 0)
{
Customer tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp;
}
}
// Bubble Sort by priority: Antyodaya > BPL > APL
public static void sortByPriority(Customer[] arr)
{
int n = arr.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (rank(arr[j].getCategory()) > rank(arr[j+1].getCategory()))
{
Customer tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp;
}
}
// Insertion Sort by name — O(n²), efficient for nearly sorted data
public static void insertionSortByName(Customer[] arr)
{
for (int i = 1; i < arr.length; i++)
{
Customer key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j].getName().compareToIgnoreCase(key.getName()) > 0)
{
arr[j+1] = arr[j]; j--;
}
arr[j+1] = key;
}
}
private static int rank(String cat)
{
switch (cat.toUpperCase())
{
case "ANTYODAYA": return 1;
case "BPL": return 2;
case "APL": return 3;
default: return 4;
}
}
}
// BINARY SEARCH (DSA: O(log n))
class BinarySearchCard
{
public static int search(String[] cards, String target)
{
int low = 0, high = cards.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
int cmp = cards[mid].compareToIgnoreCase(target);
if (cmp == 0) return mid;
else if (cmp < 0) low = mid + 1;
else high = mid - 1;
}
return -1;
}
}
// OTP MANAGER (DSA: HASH MAP)
class OTPManager
{
private static Map<String, OTPData> otpStore = new HashMap<>();
private static Map<String, Integer> attemptCount = new HashMap<>();
static class OTPData
{
String otp;
long expiryTime;
OTPData(String otp, long expiryTime)
{
this.otp = otp;
this.expiryTime = expiryTime;
}
}
// Generate OTP, valid 2 minutes
public static String generateOTP(String cardId)
{
String otp = String.format("%04d", new Random().nextInt(10000));
long expiryTime = System.currentTimeMillis() + 120_000L;
otpStore.put(cardId, new OTPData(otp, expiryTime));
attemptCount.put(cardId, 0);
return otp;
}
// Verify OTP — max 3 attempts, 2-minute expiry
public static boolean verifyOTP(String cardId, String entered)
{
int attempts = attemptCount.getOrDefault(cardId, 0);
if (attempts >= 3) return false;
OTPData data = otpStore.get(cardId);
if (data == null)
{
attemptCount.put(cardId, attempts + 1);
return false;
}
if (System.currentTimeMillis() > data.expiryTime)
{
otpStore.remove(cardId);
return false;
}
if (data.otp.equals(entered))
{
otpStore.remove(cardId);
attemptCount.remove(cardId);
return true;
}
attemptCount.put(cardId, attempts + 1);
return false;
}
// Mask phone: first 2 + ****** + last 2
public static String maskPhone(String phone)
{
if (phone == null || phone.length() < 10) return phone;
return phone.substring(0, 2) + "******" + phone.substring(phone.length() - 2);
}
}
// MAIN DRIVER
public class RationDistributionSystem
{
public static void main(String[] args)
{
System.out.println(" DIGITAL RATION DISTRIBUTION SYSTEM ");
// 1. Create shops per state (Array storage)
Shop shopHaryana = buildShop("Haryana");
Shop shopWestBengal= buildShop("West Bengal");
shopHaryana.displayStock();
shopWestBengal.displayStock();
// 2. Add beneficiaries to Linked List
BeneficiaryList beneficiaries = new BeneficiaryList();
beneficiaries.addBeneficiary(new Customer("Amarjeet Singh", 45, "9876543210", "RC101", "BPL", "Sector-10", "Haryana"));
beneficiaries.addBeneficiary(new Customer("Baldev Singh", 38, "9876543211", "RC102", "APL", "Sector-15", "Haryana"));
beneficiaries.addBeneficiary(new Customer("Mamata Devi", 52, "9876543212", "RC103", "Antyodaya", "Sector-08", "West Bengal"));
beneficiaries.addBeneficiary(new Customer("Sourav Roy", 48, "9876543213", "RC104", "BPL", "Sector-12", "West Bengal"));
beneficiaries.addBeneficiary(new Customer("Priya Nair", 55, "9876543214", "RC105", "APL", "Sector-08", "Kerala"));
beneficiaries.displayAll();
// 3. Linear search on Linked List
System.out.println("\n--- Linear Search: RC103 ---");
Customer found = beneficiaries.searchByCard("RC103");
if (found != null)
{
System.out.println("VERIFIED");
found.displayDetails();
}
else System.out.println("Card not found.");
// 4. Sort by priority (Bubble Sort)
Customer[] arr = beneficiaries.toArray();
SortBeneficiaries.sortByPriority(arr);
System.out.println("\n--- Sorted by Priority (Antyodaya > BPL > APL) ---");
for (Customer c : arr) c.displayDetails();
// 5. Sort by area (Bubble Sort)
SortBeneficiaries.sortByArea(arr);
System.out.println("\n--- Sorted by Area ---");
for (Customer c : arr) c.displayDetails();
// 6. Sort by name (Insertion Sort)
SortBeneficiaries.insertionSortByName(arr);
System.out.println("\n--- Sorted by Name (Insertion Sort) ---");
for (Customer c : arr) c.displayDetails();
// 7. Binary search on sorted card IDs
String[] cardIds = {"RC101","RC102","RC103","RC104","RC105"};
Arrays.sort(cardIds);
int idx = BinarySearchCard.search(cardIds, "RC104");
System.out.println("\n--- Binary Search: RC104 ---");
System.out.println(idx != -1 ? "Found at index " + idx : "Not found");
// 8. OTP demo
System.out.println("\n--- OTP Demo (RC101) ---");
String otp = OTPManager.generateOTP("RC101");
System.out.println("Generated OTP: " + otp);
System.out.println("Masked phone: " + OTPManager.maskPhone("9876543210"));
System.out.println("Verify correct: " + OTPManager.verifyOTP("RC101", otp));
// 9. Queue: sort by priority then enqueue
DistributionQueue dq = new DistributionQueue();
SortBeneficiaries.sortByPriority(arr);
for (Customer c : arr) dq.enqueue(c);
dq.displayQueue();
// 10. Dequeue (FIFO) → served, pushed to Stack (LIFO)
System.out.println("\n--- Distributing Ration (FIFO) ---");
while (!dq.isEmpty())
{
Customer next = dq.dequeue();
System.out.println("Served: " + next.getName() +
" | Card: " + next.getRationCardId() +
" | Category: " + next.getCategory());
}
// 11. Check status via stack
System.out.println("\n--- Distribution Status ---");
String[] checkIds = {"RC101","RC103","RC105"};
for (String id : checkIds)
System.out.println(id + " => " + dq.getStatus(id));
System.out.println(" All beneficiaries served successfully.");
}
private static Shop buildShop(String state) {
Shop shop = new Shop("S_" + state.replaceAll(" ","").toUpperCase(),
"Government Ration Shop", "Main Market", state, 5);
if (state.equals("Punjab") || state.equals("Haryana")) {
shop.addItem(new Inventory("Rice", 800, 3.0, 200));
shop.addItem(new Inventory("Wheat", 1500, 2.5, 300));
shop.addItem(new Inventory("Sugar", 400, 13.5, 100));
shop.addItem(new Inventory("Oil", 250, 80.0, 80));
} else if (state.equals("West Bengal")) {
shop.addItem(new Inventory("Rice", 1200, 3.0, 300));
shop.addItem(new Inventory("Wheat", 500, 2.5, 150));
shop.addItem(new Inventory("Sugar", 350,13.5, 100));
shop.addItem(new Inventory("Oil", 200,80.0, 60));
} else if (state.equals("Kerala")) {
shop.addItem(new Inventory("Rice", 1000, 3.0, 250));
shop.addItem(new Inventory("Wheat", 600, 2.5, 150));
shop.addItem(new Inventory("Sugar", 300,13.5, 80));
shop.addItem(new Inventory("Oil", 180,80.0, 50));
} else {
shop.addItem(new Inventory("Rice", 700, 3.0, 200));
shop.addItem(new Inventory("Wheat", 700, 2.5, 200));
shop.addItem(new Inventory("Sugar", 300,13.5, 80));
shop.addItem(new Inventory("Oil", 150,80.0, 50));
}
return shop;
}
}