-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCrabSubmarineFuelSaver.java
More file actions
73 lines (68 loc) · 2.62 KB
/
CrabSubmarineFuelSaver.java
File metadata and controls
73 lines (68 loc) · 2.62 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
import java.util.Arrays;
import java.util.List;
/**
* Solution to Day 7: The Treachery of Whales.
*
* @author bluebillxp
*/
public class CrabSubmarineFuelSaver {
public static void main(String[] args) {
List<String> input = AdventHelper.readInput("input-day7-the-treachery-of-whales.txt");
String[] strValues = input.get(0).split(",");
int[] crabPositions = new int[strValues.length];
for (int i = 0; i < strValues.length; i++) {
crabPositions[i] = Integer.valueOf(strValues[i]);
}
Arrays.sort(crabPositions);
System.out.println("Day 7: The Treachery of Whales " + crabPositions.length + " crabs located.");
System.out.println("Day 7: The Treachery of Whales --- Part One ---");
System.out.println("How much fuel must they spend to align to that position?");
final int answerOne = solutionPartOne(crabPositions);
System.out.println("Answer: " + answerOne);
System.out.println("\nDay 7: The Treachery of Whales --- Part Two ---");
System.out.println("How much fuel must they spend to align to that position?");
final long answerTwo = solutionPartTwo(crabPositions);
System.out.println("Answer: " + answerTwo);
}
/**
* Calculates how much fuel must they spend to align to that position.
*
* @param crabPositions Defined positions of crabs from the challenge.
*
* @return answer
*/
private static int solutionPartOne(int[] crabPositions) {
int median = 0;
if (crabPositions.length % 2 == 0) {
median = ((crabPositions[crabPositions.length/2] + crabPositions[((crabPositions.length/2) - 1)]) / 2);
} else {
median = crabPositions[crabPositions.length/2];
}
int fuelSpent = 0;
for (int crabPos : crabPositions) {
fuelSpent += Math.abs(crabPos - median);
}
return fuelSpent;
}
/**
* Calculates how much fuel must they spend to align to that position.
*
* @param crabPositions Defined positions of crabs from the challenge.
*
* @return answer
*/
private static long solutionPartTwo(int[] crabPositions) {
int totalSum = 0;
for (int crabPos : crabPositions) {
totalSum += crabPos;
}
double avg = Math.floor((double) totalSum / (double) crabPositions.length);
int fuelSpent = 0;
for (int crabPos : crabPositions) {
for (int crabFuel = 1; crabFuel <= Math.abs(crabPos - avg); crabFuel++) {
fuelSpent += crabFuel;
}
}
return fuelSpent;
}
}