-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDriver.java
More file actions
822 lines (702 loc) · 34.1 KB
/
Driver.java
File metadata and controls
822 lines (702 loc) · 34.1 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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Driver {
static class InsuranceRecord {
int age;
String sex;
double bmi;
int children;
String smoker;
String region;
double charges;
InsuranceRecord(int age, String sex, double bmi, int children, String smoker, String region, double charges) {
this.age = age;
this.sex = sex;
this.bmi = bmi;
this.children = children;
this.smoker = smoker;
this.region = region;
this.charges = charges;
}
@Override
public String toString() {
return String.format(
"Age: %d | Sex: %s | BMI: %.2f | Children: %d | Smoker: %s | Region: %s | Charges: %.2f",
age, sex, bmi, children, smoker, region, charges
);
}
}
// ---- Load first N records from CSV ----
static List<Driver.InsuranceRecord> loadFirstN(String csvPath, int N) throws IOException {
List<InsuranceRecord> out = new ArrayList<>();
try (BufferedReader br = Files.newBufferedReader(Paths.get(csvPath))) {
String header = br.readLine(); // skip header
if (header == null) throw new IOException("Empty CSV (no header).");
String line;
int count = 0;
while ((line = br.readLine()) != null && count < N) {
if (line.isEmpty()) continue;
String[] parts = line.split(",", -1); // keep empty trailing fields
if (parts.length < 7) continue; // skip malformed lines
InsuranceRecord r = new InsuranceRecord(
Integer.parseInt(parts[0].trim()), // age
parts[1].trim(), // sex
Double.parseDouble(parts[2].trim()), // bmi
Integer.parseInt(parts[3].trim()), // children
parts[4].trim(), // smoker
parts[5].trim(), // region
Double.parseDouble(parts[6].trim()) // charges
);
out.add(r);
count++;
}
}
return out;
}
// ---------- Histogram utilities (ages) ----------
static List<Integer> agesFrom(List<InsuranceRecord> records) {
List<Integer> ages = new ArrayList<>(records.size());
for (InsuranceRecord r : records) ages.add(r.age);
return ages;
}
static void printPerAgeHistogram(List<Integer> ages, int maxWidth) {
if (ages.isEmpty()) { System.out.println("No ages to plot."); return; }
Map<Integer, Integer> freq = new TreeMap<>();
for (int a : ages) freq.merge(a, 1, Integer::sum);
int maxCount = freq.values().stream().mapToInt(Integer::intValue).max().orElse(1);
System.out.println("\nHorizontal Histogram (per age):");
for (Map.Entry<Integer, Integer> e : freq.entrySet()) {
int age = e.getKey(), count = e.getValue();
System.out.printf("%3d: %s (%d)%n", age, bar(count, maxCount, maxWidth), count);
}
}
static void printBinnedHistogram(List<Integer> ages, int binSize, int maxWidth) {
if (ages.isEmpty()) { System.out.println("No ages to plot."); return; }
int min = ages.stream().mapToInt(i -> i).min().orElse(0);
int max = ages.stream().mapToInt(i -> i).max().orElse(0);
int start = (int) Math.floor(min / (double) binSize) * binSize;
int end = (int) Math.ceil((max + 1) / (double) binSize) * binSize - 1;
Map<String, Integer> bins = new LinkedHashMap<>();
for (int lo = start; lo <= end; lo += binSize) {
int hi = lo + binSize - 1;
bins.put(String.format("%d-%d", lo, hi), 0);
}
for (int a : ages) {
int lo = (a / binSize) * binSize;
int hi = lo + binSize - 1;
String label = String.format("%d-%d", lo, hi);
if (!bins.containsKey(label)) {
if (a < start) label = String.format("%d-%d", start, start + binSize - 1);
else label = String.format("%d-%d", end - binSize + 1, end);
}
bins.put(label, bins.get(label) + 1);
}
int maxCount = bins.values().stream().mapToInt(Integer::intValue).max().orElse(1);
int labelWidth = bins.keySet().stream().mapToInt(String::length).max().orElse(7);
System.out.printf("\nHorizontal Histogram (bins, size=%d):%n", binSize);
for (Map.Entry<String, Integer> e : bins.entrySet()) {
String label = e.getKey();
int count = e.getValue();
System.out.printf("%" + labelWidth + "s: %s (%d)%n", label, bar(count, maxCount, maxWidth), count);
}
}
static String bar(int count, int maxCount, int maxWidth) {
if (count <= 0 || maxCount <= 0) return "";
int len = (int) Math.round((count * 1.0 / maxCount) * maxWidth);
len = Math.max(len, 1); // show at least one '#'
char[] arr = new char[len];
Arrays.fill(arr, '#');
return new String(arr);
}
// ---------- Children counts ----------
/** Returns counts keyed by number of children (0,1,2,...) sorted ascending. */
static Map<Integer, Integer> childrenCounts(List<InsuranceRecord> records) {
Map<Integer, Integer> counts = new TreeMap<>();
for (InsuranceRecord r : records) {
counts.merge(r.children, 1, Integer::sum);
}
return counts;
}
static void printChildrenCounts(Map<Integer, Integer> counts) {
System.out.println("\nTotal records by number of children:");
for (Map.Entry<Integer, Integer> e : counts.entrySet()) {
System.out.printf("children=%d -> %d record(s)%n", e.getKey(), e.getValue());
}
}
// ---------- Feature 02: summary stats ----------
static class Stats {
long count = 0;
double sum = 0.0;
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
void add(double v) {
count++; sum += v;
if (v < min) min = v;
if (v > max) max = v;
}
double avg() { return count == 0 ? 0.0 : sum / count; }
}
static Map<String, Stats> computeFeature02Stats(List<InsuranceRecord> records) {
Stats age = new Stats(), bmi = new Stats(), children = new Stats(), charges = new Stats();
for (InsuranceRecord r : records) {
age.add(r.age);
bmi.add(r.bmi);
children.add(r.children);
charges.add(r.charges);
}
Map<String, Stats> map = new LinkedHashMap<>();
map.put("age", age);
map.put("bmi", bmi);
map.put("children", children);
map.put("charges", charges);
return map;
}
static void printFeature02(Map<String, Stats> stats) {
System.out.println("\n=== Feature 02: Stats for age, bmi, children, and charges ===");
System.out.printf("%-10s %8s %12s %12s %12s%n", "column", "count", "min", "max", "avg");
System.out.println("--------------------------------------------------------------");
for (Map.Entry<String, Stats> e : stats.entrySet()) {
Stats s = e.getValue();
System.out.printf("%-10s %8d %12.2f %12.2f %12.2f%n",
e.getKey(), s.count, s.min, s.max, s.avg());
}
}
// ---------- Feature 04: vertical BMI histogram ----------
public static Map<Integer, Integer> feature04_bmiBins(List<InsuranceRecord> records, int binSize) {
Map<Integer, Integer> bins = new TreeMap<>();
for (InsuranceRecord r : records) {
int b = ((int) Math.floor(r.bmi / binSize)) * binSize;
bins.put(b, bins.getOrDefault(b, 0) + 1);
}
return bins;
}
public static void printFeature04(Map<Integer, Integer> bins) {
int peak = 1;
for (int v : bins.values()) peak = Math.max(peak, v);
for (int level = peak; level >= 1; level--) {
StringBuilder row = new StringBuilder();
for (int b : bins.keySet()) {
int count = bins.get(b);
row.append(count >= level ? " # " : " ");
}
System.out.println(row);
}
StringBuilder base = new StringBuilder();
for (int b : bins.keySet()) {
base.append(String.format("%2d ", b));
}
System.out.println(base);
}
// ---------- Feature 06: smokers vs non-smokers (vertical) ----------
public static Map<String, Integer> feature06_smokerCounts(List<InsuranceRecord> records) {
Map<String, Integer> counts = new LinkedHashMap<>();
counts.put("smoker", 0);
counts.put("non-smoker", 0);
for (InsuranceRecord r : records) {
if ("yes".equalsIgnoreCase(r.smoker)) {
counts.put("smoker", counts.get("smoker") + 1);
} else {
counts.put("non-smoker", counts.get("non-smoker") + 1);
}
}
return counts;
}
public static void printFeature06(Map<String, Integer> counts) {
int max = 1;
for (int v : counts.values()) max = Math.max(max, v);
for (int level = max; level >= 1; level--) {
StringBuilder row = new StringBuilder();
for (String k : counts.keySet()) {
int c = counts.get(k);
row.append(c >= level ? " # " : " ");
}
System.out.println(row);
}
System.out.println(" S NS ");
}
static Map<String,Integer> regionCounts(List<InsuranceRecord> records) {
Map<String,Integer> m = new TreeMap<>();
for (InsuranceRecord r : records) m.merge(r.region.toLowerCase(), 1, Integer::sum);
return m;
}
static boolean feature07_fairWithin5Percent(List<InsuranceRecord> records) {
Map<String,Integer> m = regionCounts(records);
int total = m.values().stream().mapToInt(i->i).sum();
if (total == 0 || m.isEmpty()) return false;
double min = 1.0, max = 0.0;
for (int c : m.values()) {
double p = c / (double) total;
if (p < min) min = p;
if (p > max) max = p;
}
return (max - min) <= 0.05 + 1e-12;
}
// ---------- Feature 08: >=50 avg charges at least 2x <=20 ----------
public static boolean feature08_oldVsYoungCharges(List<InsuranceRecord> records) {
double oldSum = 0.0;
double youngSum = 0.0;
int oldCount = 0;
int youngCount = 0;
for (InsuranceRecord r : records) {
if (r.age >= 50) { oldSum += r.charges; oldCount++; }
if (r.age <= 20) { youngSum += r.charges; youngCount++; }
}
if (oldCount == 0 || youngCount == 0) return false;
double oldAvg = oldSum / oldCount;
double youngAvg = youngSum / youngCount;
return oldAvg >= 2.0 * youngAvg;
}
static boolean feature09_bmi30to45HasWiderChargeRange(List<InsuranceRecord> records) {
double lMin=Double.POSITIVE_INFINITY,lMax=Double.NEGATIVE_INFINITY;
double mMin=Double.POSITIVE_INFINITY,mMax=Double.NEGATIVE_INFINITY;
double hMin=Double.POSITIVE_INFINITY,hMax=Double.NEGATIVE_INFINITY;
boolean l=false,m=false,h=false;
for (InsuranceRecord r : records) {
if (r.bmi < 30) { l=true; if (r.charges<lMin) lMin=r.charges; if (r.charges>lMax) lMax=r.charges; }
else if (r.bmi <= 45) { m=true; if (r.charges<mMin) mMin=r.charges; if (r.charges>mMax) mMax=r.charges; }
else { h=true; if (r.charges<hMin) hMin=r.charges; if (r.charges>hMax) hMax=r.charges; }
}
double lr = l ? lMax - lMin : 0, mr = m ? mMax - mMin : 0, hr = h ? hMax - hMin : 0;
return mr > lr && mr > hr;
}
// ---------- Feature 10: more children ⇒ lower charge per child (monotone?) ----------
public static boolean feature10_lowerChargePerChild(List<InsuranceRecord> records) {
Map<Integer, List<Double>> groups = new TreeMap<>();
for (InsuranceRecord r : records) {
groups.computeIfAbsent(r.children, k -> new ArrayList<>()).add(r.charges);
}
double prev = Double.MAX_VALUE; // expect per-child avg to be nonincreasing as children↑
for (int c : groups.keySet()) {
List<Double> list = groups.get(c);
double sum = 0.0;
for (double v : list) sum += v;
double avg = list.isEmpty() ? 0.0 : sum / list.size();
double perChild = (c == 0) ? avg : avg / c;
if (perChild > prev) return false; // broke the nonincreasing condition
prev = perChild;
}
return true;
}
// ---------- Feature 12: south smokers ≥25% more than other smokers ----------
public static boolean feature12_southSmokers(List<InsuranceRecord> records) {
double southSum = 0.0;
double otherSum = 0.0;
int southCount = 0;
int otherCount = 0;
for (InsuranceRecord r : records) {
if (r.smoker.equalsIgnoreCase("yes")) {
String reg = r.region.toLowerCase();
if (reg.contains("south")) {
southSum += r.charges;
southCount++;
} else {
otherSum += r.charges;
otherCount++;
}
}
}
if (southCount == 0 || otherCount == 0) return false;
double southAvg = southSum / southCount;
double otherAvg = otherSum / otherCount;
return southAvg >= 1.25 * otherAvg;
}
static boolean feature11_smokersHigherAvgAndWider(List<InsuranceRecord> records) {
double sSum=0,nSum=0; int sCnt=0,nCnt=0;
double sMin=Double.POSITIVE_INFINITY,sMax=Double.NEGATIVE_INFINITY;
double nMin=Double.POSITIVE_INFINITY,nMax=Double.NEGATIVE_INFINITY;
for (InsuranceRecord r : records) {
if ("yes".equalsIgnoreCase(r.smoker)) {
sSum += r.charges; sCnt++; if (r.charges<sMin) sMin=r.charges; if (r.charges>sMax) sMax=r.charges;
} else {
nSum += r.charges; nCnt++; if (r.charges<nMin) nMin=r.charges; if (r.charges>nMax) nMax=r.charges;
}
}
if (sCnt==0 || nCnt==0) return false;
double sAvg = sSum/sCnt, nAvg = nSum/nCnt;
double sRange = sMax - sMin, nRange = nMax - nMin;
return sAvg > nAvg && sRange > nRange;
}
static boolean feature13_smokersLowerBmi(List<InsuranceRecord> records) {
double sSum=0,nSum=0; int sCnt=0,nCnt=0;
for (InsuranceRecord r : records) {
if ("yes".equalsIgnoreCase(r.smoker)) { sSum+=r.bmi; sCnt++; }
else { nSum+=r.bmi; nCnt++; }
}
if (sCnt==0 || nCnt==0) return false;
return (sSum/sCnt) < (nSum/nCnt);
}
// ---------- Feature 14: smoker age distribution ----------
public static Map<Integer, Integer> feature14_smokerAgeDist(List<InsuranceRecord> records) {
Map<Integer, Integer> dist = new TreeMap<>();
for (InsuranceRecord r : records) {
if (r.smoker.equalsIgnoreCase("yes")) {
dist.put(r.age, dist.getOrDefault(r.age, 0) + 1);
}
}
return dist;
}
static List<Map.Entry<String,Double>> feature15_regionsByAvgChargesDesc(List<InsuranceRecord> records) {
Map<String,double[]> acc = new TreeMap<>();
for (InsuranceRecord r : records) {
String k = r.region.toLowerCase();
acc.computeIfAbsent(k, t -> new double[2]);
double[] a = acc.get(k);
a[0] += r.charges; a[1] += 1.0;
}
List<Map.Entry<String,Double>> out = new ArrayList<>();
for (Map.Entry<String,double[]> e : acc.entrySet())
out.add(Map.entry(e.getKey(), e.getValue()[1]==0?0:e.getValue()[0]/e.getValue()[1]));
out.sort((a,b)->Double.compare(b.getValue(), a.getValue()));
return out;
}
// ---------- Feature 16: avg ages smokers vs non-smokers ----------
public static Map<String, Double> feature16_avgAges(List<InsuranceRecord> records) {
double smokerSum = 0.0, nonSum = 0.0;
int smokerCount = 0, nonCount = 0;
for (InsuranceRecord r : records) {
if (r.smoker.equalsIgnoreCase("yes")) {
smokerSum += r.age;
smokerCount++;
} else {
nonSum += r.age;
nonCount++;
}
}
Map<String, Double> out = new LinkedHashMap<>();
out.put("smoker_avg_age", smokerCount == 0 ? 0.0 : smokerSum / smokerCount);
out.put("nonsmoker_avg_age", nonCount == 0 ? 0.0 : nonSum / nonCount);
return out;
}
static double[] feature17_southVsNorthSmokingRatesAndAvgAge(List<InsuranceRecord> records) {
int sCount=0,nCount=0,sSmokers=0,nSmokers=0; double sAgeSum=0,nAgeSum=0;
for (InsuranceRecord r : records) {
String reg = r.region.toLowerCase();
if (reg.contains("south")) { sCount++; sAgeSum+=r.age; if ("yes".equalsIgnoreCase(r.smoker)) sSmokers++; }
else if (reg.contains("north")) { nCount++; nAgeSum+=r.age; if ("yes".equalsIgnoreCase(r.smoker)) nSmokers++; }
}
double sRate = sCount==0?0:(sSmokers/(double)sCount);
double nRate = nCount==0?0:(nSmokers/(double)nCount);
double sAvgAge = sCount==0?0:(sAgeSum/sCount);
return new double[]{sRate, nRate, sAvgAge};
}
// ---------- Feature 18: avg BMI south vs north ----------
public static Map<String, Double> feature18_bmiSouthNorth(List<InsuranceRecord> records) {
double southSum = 0.0, northSum = 0.0;
int southCount = 0, northCount = 0;
for (InsuranceRecord r : records) {
String reg = r.region.toLowerCase();
if (reg.contains("south")) {
southSum += r.bmi;
southCount++;
} else if (reg.contains("north")) {
northSum += r.bmi;
northCount++;
}
}
Map<String, Double> out = new LinkedHashMap<>();
out.put("south_avg_bmi", southCount == 0 ? 0.0 : southSum / southCount);
out.put("north_avg_bmi", northCount == 0 ? 0.0 : northSum / northCount);
return out;
}
static Map<String,Double> feature19_childrenSouthVsNorthAges(List<InsuranceRecord> records) {
double sKids=0,nKids=0, sAge=0,nAge=0; int sCnt=0,nCnt=0;
for (InsuranceRecord r : records) {
String reg = r.region.toLowerCase();
if (reg.contains("south")) { sKids+=r.children; sAge+=r.age; sCnt++; }
else if (reg.contains("north")) { nKids+=r.children; nAge+=r.age; nCnt++; }
}
Map<String,Double> out = new LinkedHashMap<>();
out.put("south_avg_children", sCnt==0?0:sKids/sCnt);
out.put("north_avg_children", nCnt==0?0:nKids/nCnt);
out.put("south_avg_age", sCnt==0?0:sAge/sCnt);
out.put("north_avg_age", nCnt==0?0:nAge/nCnt);
return out;
}
// ---------- Feature 20: simple linear regression charges ~ BMI ----------
public static void feature20_regressionBMI(List<InsuranceRecord> records) {
double sumX = 0.0, sumY = 0.0, sumXY = 0.0, sumX2 = 0.0, sumY2 = 0.0;
int n = records.size();
for (InsuranceRecord r : records) {
sumX += r.bmi;
sumY += r.charges;
sumXY += r.bmi * r.charges;
sumX2 += r.bmi * r.bmi;
sumY2 += r.charges * r.charges;
}
double denomSlope = (n * sumX2 - sumX * sumX);
if (denomSlope == 0.0 || n == 0) {
System.out.println("Cannot compute regression: degenerate X variance or no data.");
return;
}
double slope = (n * sumXY - sumX * sumY) / denomSlope;
double intercept = (sumY - slope * sumX) / n;
double rNum = n * sumXY - sumX * sumY;
double rDenTermX = n * sumX2 - sumX * sumX;
double rDenTermY = n * sumY2 - sumY * sumY;
double rDen = Math.sqrt(Math.max(0.0, rDenTermX * rDenTermY));
double r = (rDen != 0.0) ? rNum / rDen : 0.0;
System.out.printf("y = %.2f + %.2f*x, r=%.3f%n", intercept, slope, r);
for (int i = 0; i <= 10; i++) {
double x = 15 + i * 3.0; // BMI values
double pred = intercept + slope * x;
System.out.printf("BMI %.1f => charges %.2f%n", x, pred);
}
}
// ==== MAIN ====
static void feature21_regressionChildren(List<InsuranceRecord> records) {
int n = records.size();
if (n==0) { System.out.println("No data."); return; }
double sx=0, sy=0, sxy=0, sx2=0, sy2=0;
for (InsuranceRecord r : records) {
double x = r.children, y = r.charges;
sx+=x; sy+=y; sxy+=x*y; sx2+=x*x; sy2+=y*y;
}
double denom = n*sx2 - sx*sx;
if (denom==0) { System.out.println("Cannot compute regression."); return; }
double slope = (n*sxy - sx*sy)/denom;
double intercept = (sy - slope*sx)/n;
double rnum = n*sxy - sx*sy;
double rden = Math.sqrt((n*sx2 - sx*sx)*(n*sy2 - sy*sy));
double r = rden==0?0:rnum/rden;
System.out.printf("y = %.6f + %.6f*x, r=%.6f%n", intercept, slope, r);
for (int i=0;i<22;i++) {
double x = i;
double y = intercept + slope*x;
System.out.printf("x=%.2f y=%.2f%n", x, y);
}
}
// ---------- Feature 22: simple linear regression charges ~ region (ordinal) ----------
private static final Map<String, Integer> REGION_CODE = new LinkedHashMap<>();
static {
REGION_CODE.put("northeast", 0);
REGION_CODE.put("northwest", 1);
REGION_CODE.put("southeast", 2);
REGION_CODE.put("southwest", 3);
}
// Container for regression summary
static class RegressionStats {
int n;
double meanX, meanY;
double sdX, sdY;
double covXY;
double r;
double a, b; // Model: y = a + b*x
}
// Compute simple linear regression and Pearson r for lists X (charges) and Y (region code)
static RegressionStats fitSimpleLinearRegression(List<Double> X, List<Double> Y) {
if (X.size() != Y.size()) throw new IllegalArgumentException("X and Y sizes differ.");
int n = X.size();
double sumX = 0, sumY = 0;
for (int i = 0; i < n; i++) { sumX += X.get(i); sumY += Y.get(i); }
double meanX = sumX / n, meanY = sumY / n;
double sxx = 0, syy = 0, sxy = 0;
for (int i = 0; i < n; i++) {
double dx = X.get(i) - meanX;
double dy = Y.get(i) - meanY;
sxx += dx * dx;
syy += dy * dy;
sxy += dx * dy;
}
double varX = sxx / (n - 1);
double varY = syy / (n - 1);
double sdX = Math.sqrt(varX);
double sdY = Math.sqrt(varY);
double covXY = sxy / (n - 1);
double b = covXY / varX; // slope
double a = meanY - b * meanX; // intercept
double r = (sdX == 0 || sdY == 0) ? 0.0 : covXY / (sdX * sdY);
RegressionStats st = new RegressionStats();
st.n = n; st.meanX = meanX; st.meanY = meanY;
st.sdX = sdX; st.sdY = sdY; st.covXY = covXY;
st.r = r; st.a = a; st.b = b;
return st;
}
// Build X (charges) and Y (region_code) from records
static void feature22_regressionChargesVsRegion(List<InsuranceRecord> records, List<Double> newCharges) {
List<Double> X = new ArrayList<>();
List<Double> Y = new ArrayList<>();
for (InsuranceRecord r : records) {
Integer code = REGION_CODE.get(r.region.toLowerCase());
if (code != null) {
X.add(r.charges);
Y.add(code.doubleValue());
}
}
if (X.size() < 2) {
System.out.println("=== Feature 22: Regression charges ~ region_code ===");
System.out.println("Not enough data to compute regression.");
return;
}
RegressionStats stats = fitSimpleLinearRegression(X, Y);
System.out.println("\n=== Feature 22: Regression of region_code ~ charges ===");
System.out.printf(Locale.US, "N = %d%n", stats.n);
System.out.printf(Locale.US, "Mean(charges) = %.4f, SD(charges) = %.4f%n", stats.meanX, stats.sdX);
System.out.printf(Locale.US, "Mean(region_code) = %.4f, SD(region_code) = %.4f%n", stats.meanY, stats.sdY);
System.out.printf(Locale.US, "Pearson r = %.6f%n", stats.r);
System.out.printf(Locale.US, "Model: y = a + b*x => a = %.8f, b = %.12f%n", stats.a, stats.b);
System.out.println("Region code mapping: " + REGION_CODE);
System.out.println("\nApply regression to 33 charges (x) and output (x, y_hat):");
if (newCharges == null || newCharges.isEmpty()) {
newCharges = demo33Charges(); // fallback to built-in 33 values
System.out.println("(Note) Using built-in 33 demo charges.");
}
if (newCharges.size() != 33) {
System.out.println("(Note) Received " + newCharges.size() + " values; expected 33.");
}
System.out.println("x (charges), y_hat (predicted region_code)");
for (double x : newCharges) {
double yhat = stats.a + stats.b * x;
System.out.printf(Locale.US, "%.2f, %.6f%n", x, yhat);
}
}
// Read 33 charges from a file (one per line). If path is null or unreadable, return empty list.
static List<Double> readChargesFile(String path) {
if (path == null) return List.of();
try {
return Files.readAllLines(Paths.get(path)).stream()
.map(String::trim)
.filter(s -> !s.isEmpty() && !s.startsWith("#"))
.map(s -> {
try { return Double.parseDouble(s); }
catch (NumberFormatException e) { return null; }
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
} catch (IOException e) {
System.err.println("Warning (Feature 22): couldn't read new charges file: " + e.getMessage());
return List.of();
}
}
// Built-in list of exactly 33 demo charges
static List<Double> demo33Charges() {
return Arrays.asList(
1234.56, 2450.00, 3120.75, 4088.90, 5123.10, 6234.55, 7350.40, 8120.00, 9055.25, 10010.99,
11234.80, 12500.00, 13890.45, 14999.99, 16010.10, 17222.22, 18500.75, 19999.95, 21005.00, 22345.67,
23500.00, 24890.30, 26000.00, 27550.40, 28999.00, 30010.10, 31555.55, 32999.99, 34000.00, 35555.55,
36999.99, 38010.00, 39500.25
);
}
// ---------- Main ----------
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java Driver <path-to-insurance.csv> <N>");
System.exit(2);
}
String path = args[0];
int N;
try {
N = Integer.parseInt(args[1]);
if (N <= 0) throw new NumberFormatException();
} catch (NumberFormatException e) {
System.err.println("N must be a positive integer.");
System.exit(2);
return;
}
try {
List<InsuranceRecord> records = loadFirstN(path, N);
System.out.println("=== Feature 01: Stored First N Records ===");
System.out.println("Stored " + records.size() + " records:");
for (int i = 0; i < records.size(); i++) {
System.out.printf("#%d %s%n", i + 1, records.get(i));
}
// Feature 02: summary stats
Map<String, Stats> stats = computeFeature02Stats(records);
printFeature02(stats);
// Feature 03: age horizontal histogram (per age)
System.out.println("\n=== Feature 03: Age Horizontal Histogram (per age) ===");
List<Integer> ages = agesFrom(records);
printPerAgeHistogram(ages, 50);
// Feature 04: BMI vertical histogram (bin=5)
Map<Integer, Integer> bmiBins = feature04_bmiBins(records, 5);
System.out.println("\n=== Feature 04: BMI Vertical Histogram (bin=5) ===");
printFeature04(bmiBins);
System.out.println("\n=== Feature 05: Age Histograms (per age and binned) ===");
printBinnedHistogram(ages, 5, 50);
// Feature 06: smokers vs non-smokers
Map<String, Integer> smokeCounts = feature06_smokerCounts(records);
System.out.println("\n=== Feature 06: Smokers vs Non-Smokers (Vertical) ===");
printFeature06(smokeCounts);
System.out.println("\n=== Feature 07: Region Fairness (≤5% spread) ===");
Map<String,Integer> rc = regionCounts(records);
int total = rc.values().stream().mapToInt(i->i).sum();
for (Map.Entry<String,Integer> e : rc.entrySet()) {
double p = total==0?0:(e.getValue()/(double)total)*100.0;
System.out.printf("%-10s : %4d (%.2f%%)%n", e.getKey(), e.getValue(), p);
}
System.out.println(feature07_fairWithin5Percent(records) ? "FAIR: TRUE" : "FAIR: FALSE");
// Feature 08
System.out.println("\n=== Feature 08: Avg charges age>=50 at least 2x age<=20 ? ===");
System.out.println(feature08_oldVsYoungCharges(records) ? "TRUE" : "FALSE");
System.out.println("\n=== Feature 09: BMI 30–45 has widest charge range? ===");
System.out.println(feature09_bmi30to45HasWiderChargeRange(records) ? "TRUE" : "FALSE");
// Feature 10
System.out.println("\n=== Feature 10: More children ⇒ lower charge per child (monotone) ? ===");
System.out.println(feature10_lowerChargePerChild(records) ? "TRUE" : "FALSE");
System.out.println("\n=== Feature 11: Smokers higher avg charges AND wider range? ===");
System.out.println(feature11_smokersHigherAvgAndWider(records) ? "TRUE" : "FALSE");
// Feature 12
System.out.println("\n=== Feature 12: South smokers pay ≥25% more than other smokers ? ===");
System.out.println(feature12_southSmokers(records) ? "TRUE" : "FALSE");
System.out.println("\n=== Feature 13: Do smokers average lower BMI? ===");
System.out.println(feature13_smokersLowerBmi(records) ? "TRUE" : "FALSE");
// Feature 14
System.out.println("\n=== Feature 14: Smoker Age Distribution (age -> count) ===");
for (Map.Entry<Integer, Integer> e : feature14_smokerAgeDist(records).entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
// Feature 15
System.out.println("\n=== Feature 15: Regions by Average Charges (desc) ===");
for (Map.Entry<String,Double> e : feature15_regionsByAvgChargesDesc(records))
System.out.printf("%-12s -> %.2f%n", e.getKey(), e.getValue());
// Feature 16
System.out.println("\n=== Feature 16: Avg Age (smokers vs non-smokers) ===");
Map<String, Double> f16 = feature16_avgAges(records);
System.out.printf("smoker_avg_age: %.2f%n", f16.get("smoker_avg_age"));
System.out.printf("nonsmoker_avg_age: %.2f%n", f16.get("nonsmoker_avg_age"));
System.out.println("\n=== Feature 17: Southerners smoke more than northerners? If yes, at what avg age ===");
double[] s17 = feature17_southVsNorthSmokingRatesAndAvgAge(records);
System.out.printf("south_smoke_rate=%.6f north_smoke_rate=%.6f%n", s17[0], s17[1]);
if (s17[0] > s17[1]) System.out.printf("TRUE at south average age: %.2f%n", s17[2]);
else System.out.println("FALSE");
// Feature 18
System.out.println("\n=== Feature 18: Avg BMI (south vs north) ===");
Map<String, Double> f18 = feature18_bmiSouthNorth(records);
System.out.printf("south_avg_bmi: %.2f%n", f18.get("south_avg_bmi"));
System.out.printf("north_avg_bmi: %.2f%n", f18.get("north_avg_bmi"));
System.out.println("\n=== Feature 19: Southerners average more children than northerners? At what avg age ===");
Map<String,Double> s19 = feature19_childrenSouthVsNorthAges(records);
boolean moreKids = s19.get("south_avg_children") > s19.get("north_avg_children");
System.out.printf("south_avg_children=%.2f north_avg_children=%.2f%n", s19.get("south_avg_children"), s19.get("north_avg_children"));
System.out.printf("south_avg_age=%.2f north_avg_age=%.2f%n", s19.get("south_avg_age"), s19.get("north_avg_age"));
System.out.println(moreKids ? "TRUE at south average age above" : "FALSE");
// Feature 20
System.out.println("\n=== Feature 20: Regression charges ~ BMI ===");
feature20_regressionBMI(records);
// Extra: age histograms + children counts
printBinnedHistogram(ages, 5, 50);
System.out.println("\n=== Feature 21: Regression charges ~ children (r + 22 predictions) ===");
feature21_regressionChildren(records);
System.out.println("\n=== Feature 22: Regression region_code ~ charges (r + 33 predictions) ===");
Map<Integer, Integer> byChildren = childrenCounts(records);
printChildrenCounts(byChildren);
List<Double> newCharges = readChargesFile(args.length == 3 ? args[2] : null);
System.out.println("\n=== Feature 22: Regression (region_code ~ charges) + Pearson r + 33 predictions ===");
feature22_regressionChargesVsRegion(records, newCharges);
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
System.exit(1);
}
}
}
// System.err.println("I/O error: " + e.getMessage())