Skip to content

Commit e4c7397

Browse files
authored
Create Day2.java
1 parent c13df4b commit e4c7397

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed

Day2.java

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
2+
/**
3+
* --- Day 2: Corruption Checksum ---
4+
*
5+
* As you walk through the door, a glowing humanoid shape yells in your
6+
* direction. "You there! Your state appears to be idle. Come help us repair the
7+
* corruption in this spreadsheet - if we take another millisecond, we'll have
8+
* to display an hourglass cursor!"
9+
*
10+
* The spreadsheet consists of rows of apparently-random numbers. To make sure
11+
* the recovery process is on the right track, they need you to calculate the
12+
* spreadsheet's checksum. For each row, determine the difference between the
13+
* largest value and the smallest value; the checksum is the sum of all of these
14+
* differences.
15+
*
16+
* For example, given the following spreadsheet:
17+
*
18+
* 5 1 9 5
19+
* 7 5 3
20+
* 2 4 6 8
21+
*
22+
* The first row's largest and smallest values are 9 and 1, and their difference is 8.
23+
* The second row's largest and smallest values are 7 and 3, and their difference is 4.
24+
* The third row's difference is 6.
25+
* In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18.
26+
*/
27+
public class Day2 {
28+
29+
public static int part1(String input) {
30+
String[] rows = input.split("\n");
31+
int result = 0;
32+
for (String row : rows) {
33+
int max = -1;
34+
int min = Integer.MAX_VALUE;
35+
String[] numbers = row.split("\t");
36+
for (String number : numbers) {
37+
int n = Integer.parseInt(number);
38+
if (max < n) {
39+
max = n;
40+
}
41+
if (min > n) {
42+
min = n;
43+
}
44+
}
45+
result += (max - min);
46+
}
47+
48+
return result;
49+
}
50+
51+
/**
52+
* Evenly divisible
53+
*
54+
* @param input
55+
* @return
56+
*/
57+
public static int part2(String input) {
58+
String[] rows = input.split("\n");
59+
int result = 0;
60+
for (String row : rows) {
61+
String[] numbers = row.split("\t");
62+
result += addDivisibles(0, 1, numbers);
63+
}
64+
65+
return result;
66+
}
67+
68+
private static int addDivisibles(int i, int j, String[] numbers) {
69+
if (i < j && j < numbers.length) {
70+
int a = Integer.parseInt(numbers[i]);
71+
int b = Integer.parseInt(numbers[j]);
72+
73+
int d = addDivisible(a, b);
74+
if (d == 0) {
75+
int x = addDivisibles(i + 1, j, numbers);
76+
if (x == 0)
77+
return addDivisibles(i, j + 1, numbers);
78+
else
79+
return x;
80+
}
81+
else
82+
return d;
83+
}
84+
else
85+
return 0;
86+
}
87+
88+
private static int addDivisible(int n, int m) {
89+
if (n % m == 0) {
90+
return n / m;
91+
}
92+
else if (m % n == 0) {
93+
return m / n;
94+
}
95+
return 0;
96+
}

0 commit comments

Comments
 (0)