-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathD1.java
90 lines (80 loc) · 2.87 KB
/
D1.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.io.*;
import java.util.HashMap;
public class D1 {
private static BufferedReader dataReader() {
// File path is passed as parameter
File file = new File("pathToYourPuzzle");
// Creating an object of BufferedReader class
// could generate FileNotFoundException (checked)
try {
BufferedReader data = new BufferedReader(new FileReader(file));
return data;
} catch (FileNotFoundException e) {
System.out.println("The file does not exist.");
return null;
}
}
private static HashMap<String, Integer> location(Integer value) {
HashMap<String, Integer> position = new HashMap<>();
// Add keys and values
position.put("value", value);
return position;
}
private static void part1() throws IOException {
BufferedReader inputData = dataReader();
String depth;
int measurement1 = 0;
int current1 = 0;
int previous1 = 0;
while ((depth = inputData.readLine()) != null) {
int depthNum = Integer.parseInt(depth);
current1 = depthNum;
if (current1 > previous1) {
measurement1 += 1;
}
previous1 = current1;
}
System.out.println(String.format("part 1: %s", measurement1-1));
}
private static void part2() throws IOException {
BufferedReader inputData = dataReader();
String depth;
int current2 = 0;
int previous2 = 0;
int measurement2 = 0;
Integer pointer = 0;
HashMap<String, Integer> first = location(0);
HashMap<String, Integer> second = location(0);
HashMap<String, Integer> third = location(0);
while ((depth = inputData.readLine()) != null) {
int depthNum = Integer.parseInt(depth);
// update three values
if (pointer == 0) {
first = location(depthNum);
} else if (pointer == 1) {
second = location(depthNum);
} else {
third = location(depthNum);
}
// reset pointer
if (pointer < 2) {
pointer += 1;
} else {
pointer = 0;
}
// calculate the sum of the three values
if (first.get("value") != 0 && second.get("value") != 0 && third.get("value") != 0) {
current2 = first.get("value") + second.get("value") + third.get("value");
if (current2 > previous2) {
measurement2 += 1;
}
previous2 = current2;
}
}
System.out.println(String.format("part 2: %s", measurement2-1));
}
public static void main(String[] args) throws Exception {
part1();
part2();
}
}