-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubmarinePilot.java
More file actions
82 lines (75 loc) · 2.89 KB
/
SubmarinePilot.java
File metadata and controls
82 lines (75 loc) · 2.89 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
import java.util.List;
/**
* Solution to Day 2 - Dive!
*
* @author bluebillxp
*/
public class SubmarinePilot {
private static final String CMD_FORWARD = "forward";
private static final String CMD_UP = "up";
private static final String CMD_DOWN = "down";
public static void main(String[] args) {
List<String> input = AdventHelper.readInput("input-day2-dive.txt");
System.out.println("Day 2: Dive! " + input.size() + " commands loaded.");
System.out.println("Day 2: Dive! --- Part One ---");
System.out.println("What do you get if you multiply your final horizontal position by your final depth?");
final int answerOne = solutionPartOne(input);
System.out.println("Answer: " + answerOne);
System.out.println("\nDay 2: Dive! --- Part Two ---");
System.out.println("What do you get if you multiply your final horizontal position by your final depth?");
final int answerTwo = solutionPartTwo(input);
System.out.println("Answer: " + answerTwo);
}
/**
* Calculates what you get if you multiply your final horizontal
* position by your final depth.
*
* @param input Defined input from the challenge.
*
* @return answer
*/
private static int solutionPartOne(List<String> input) {
int posHorizontal = 0;
int posDepth = 0;
for (String cmd : input) {
if (cmd.startsWith(CMD_FORWARD)) {
int x = Integer.valueOf(cmd.substring(CMD_FORWARD.length() + 1));
posHorizontal += x;
} else if (cmd.startsWith(CMD_DOWN)) {
int x = Integer.valueOf(cmd.substring(CMD_DOWN.length() + 1));
posDepth += x;
} else if (cmd.startsWith(CMD_UP)) {
int x = Integer.valueOf(cmd.substring(CMD_UP.length() + 1));
posDepth -= x;
}
}
return posHorizontal * posDepth;
}
/**
* Calculates what you get if you multiply your final horizontal
* position by your final depth.
*
* @param input Defined input from the challenge.
*
* @return answer
*/
private static int solutionPartTwo(List<String> input) {
int posHorizontal = 0;
int posDepth = 0;
int posAim = 0;
for (String cmd : input) {
if (cmd.startsWith(CMD_FORWARD)) {
int x = Integer.valueOf(cmd.substring(CMD_FORWARD.length() + 1));
posHorizontal += x;
posDepth += posAim * x;
} else if (cmd.startsWith(CMD_DOWN)) {
int x = Integer.valueOf(cmd.substring(CMD_DOWN.length() + 1));
posAim += x;
} else if (cmd.startsWith(CMD_UP)) {
int x = Integer.valueOf(cmd.substring(CMD_UP.length() + 1));
posAim -= x;
}
}
return posHorizontal * posDepth;
}
}