-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathDay12.java
94 lines (82 loc) · 2.58 KB
/
Day12.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
91
92
93
94
package com.sbaars.adventofcode.year19.days;
import com.sbaars.adventofcode.year19.Day2019;
import static com.sbaars.adventofcode.util.AoCUtils.gcd;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
public class Day12 extends Day2019 {
int[][] moons = {{-5, 6, -11}, {-8, -4, -2}, {1, 16, 4}, {11, 11, -4}};
int[][] velocity = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
public Day12() {
super(12);
}
public static void main(String[] args) {
new Day12().printParts();
}
public static long lcm(long a, long b) {
return a * (b / gcd(a, b));
}
public static long lcm(long[] input) {
long result = input[0];
for (int i = 1; i < input.length; i++) result = lcm(result, input[i]);
return result;
}
@Override
public Object part1() {
for (int n = 0; n < 1000; n++) {
determineVelocity();
moveMoonsUsingVelocity();
}
int[] res = new int[moons.length];
for (int i = 0; i < res.length; i++) {
res[i] = Arrays.stream(moons[i]).map(Math::abs).sum() * Arrays.stream(velocity[i]).map(Math::abs).sum();
}
return Arrays.stream(res).sum();
}
@Override
public Object part2() {
var sets = Collections.nCopies(moons[0].length, new HashSet<>());
long[] res = new long[sets.size()];
for (long n = 0; true; n++) {
determineVelocity();
moveMoonsUsingVelocity();
for (int i = 0; i < sets.size(); i++) {
if (res[i] == 0 && !sets.get(i).add(Arrays.asList(moons[0][i], moons[1][i], moons[2][i], moons[3][i], velocity[0][i], velocity[1][i], velocity[2][i], velocity[3][i]))) {
res[i] = n;
if (Arrays.stream(res).noneMatch(x -> x == 0)) {
return lcm(res);
}
}
}
}
}
private void moveMoonsUsingVelocity() {
for (int i = 0; i < moons.length; i++) {
for (int j = 0; j < moons[0].length; j++) {
moons[i][j] += velocity[i][j];
}
}
}
private void determineVelocity() {
for (int i = 0; i < moons.length; i++) {
for (int j = i + 1; j < moons.length; j++) {
for (int dim = 0; dim < moons[0].length; dim++) {
int moon1 = moons[i][dim], moon2 = moons[j][dim];
if (moon1 < moon2) {
velocity[i][dim]++;
velocity[j][dim]--;
} else if (moon1 > moon2) {
velocity[i][dim]--;
velocity[j][dim]++;
}
}
}
}
}
short[][] copy(short[][] arr) {
short[][] myInt = new short[arr.length][];
for (int i = 0; i < arr.length; i++)
myInt[i] = arr[i].clone();
return myInt;
}
}