-
Notifications
You must be signed in to change notification settings - Fork 5
/
Day7.java
69 lines (47 loc) · 1.34 KB
/
Day7.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
package aoc21;
import java.io.File;
import java.util.Comparator;
import java.util.List;
import utils.StaticUtils;
public class Day7 {
private List<Integer> nums;
public Day7(File file) {
nums = StaticUtils.commaSeperatedIntegerFileToList(file);
nums.sort(Comparator.naturalOrder());
}
private int run1() {
int optimalDistance = 0;
// optimalDistance = median
int n = nums.size();
if(nums.size() % 2 == 0) {
optimalDistance = nums.get((n + 1) / 2 - 1);
} else {
optimalDistance = (nums.get((n + 1) / 2 - 1) + nums.get(n / 2)) / 2;
}
final int finalOptimalDistance = optimalDistance;
int fuel = nums.stream().mapToInt(num -> Math.abs(num - finalOptimalDistance)).sum();
return fuel;
}
// brute force with gauss sum
private long run2() {
int max = nums.get(nums.size() - 1);
long fuel = 0;
long minFuel = Integer.MAX_VALUE;
for(int i = 1; i < max; i++) {
for(int num : nums) {
int distance = Math.abs(num - i);
fuel += (((int) Math.pow(distance, 2) + distance)) / 2;
}
if(minFuel > fuel) {
minFuel = fuel;
fuel = 0;
}
}
return minFuel;
}
public static void main(String[] args) {
Day7 test = new Day7(new File("C:\\Users\\tmerdin\\aoc\\aoc21\\day7\\InputFile1.txt"));
System.out.println(test.run1());
System.out.println(test.run2());
}
}