Skip to content

Commit 50d2a71

Browse files
authored
Create Day6.java
1 parent eb1fd20 commit 50d2a71

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Day6.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.List;
4+
5+
public class Day6 {
6+
7+
public static int part1(int[] blocks) {
8+
List<Integer> iterations = redistributeBlocks(blocks.clone());
9+
return iterations.size() - 1;
10+
}
11+
12+
public static int part2(int[] blocks) {
13+
List<Integer> iterations = redistributeBlocks(blocks.clone());
14+
int repeat = iterations.remove(iterations.size() - 1);
15+
return iterations.size() - iterations.indexOf(repeat);
16+
}
17+
18+
private static List<Integer> redistributeBlocks(int[] blocks) {
19+
List<Integer> iterations = new ArrayList<>();
20+
int hashCode = Arrays.hashCode(blocks);
21+
while (!iterations.contains(hashCode)) {
22+
23+
// find max
24+
int max = -1;
25+
int idx = 0;
26+
for (int i = 0; i < blocks.length; i++) {
27+
if (blocks[i] > max) {
28+
max = blocks[i];
29+
idx = i;
30+
}
31+
}
32+
33+
// redistribute
34+
blocks[idx] = 0;
35+
while (max-- > 0) {
36+
idx = (idx + 1) % blocks.length;
37+
blocks[idx]++;
38+
}
39+
40+
// log iteration
41+
iterations.add(hashCode);
42+
hashCode = Arrays.hashCode(blocks);
43+
}
44+
45+
iterations.add(hashCode);
46+
return iterations;
47+
}
48+
49+
}

0 commit comments

Comments
 (0)