-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathDay5.java
94 lines (85 loc) · 2.93 KB
/
Day5.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.year21.days;
import com.sbaars.adventofcode.year21.Day2021;
import java.awt.*;
import java.util.HashSet;
import java.util.Set;
import static com.sbaars.adventofcode.util.DataMapper.readString;
public class Day5 extends Day2021 {
public Day5() {
super(5);
}
public static void main(String[] args) {
new Day5().printParts(1);
}
@Override
public Object part1() {
var in = dayStream().map(e -> readString(e, "%n,%n -> %n,%n", Coords.class)).toList();
Set<Point> all = new HashSet<>();
Set<Point> vis = new HashSet<>();
for (Coords c : in) {
if (c.x1 == c.x2) {
for (long y = Math.min(c.y1, c.y2); y <= Math.max(c.y1, c.y2); y++) {
var l = new Point(Math.toIntExact(c.x1), Math.toIntExact(y));
if (!all.add(l)) {
vis.add(l);
}
}
} else if (c.y1 == c.y2) {
for (long x = Math.min(c.x1, c.x2); x <= Math.max(c.x1, c.x2); x++) {
var l = new Point(Math.toIntExact(x), Math.toIntExact(c.y1));
if (!all.add(l)) {
vis.add(l);
}
}
}
}
return vis.size();
}
@Override
public Object part2() {
var in = dayStream().map(e -> readString(e, "%n,%n -> %n,%n", Coords.class)).toList();
Set<Point> all = new HashSet<>();
Set<Point> vis = new HashSet<>();
for (Coords c : in) {
if (c.x1 == c.x2) {
for (long y = Math.min(c.y1, c.y2); y <= Math.max(c.y1, c.y2); y++) {
var l = new Point(Math.toIntExact(c.x1), Math.toIntExact(y));
if (!all.add(l)) {
vis.add(l);
}
}
} else if (c.y1 == c.y2) {
for (long x = Math.min(c.x1, c.x2); x <= Math.max(c.x1, c.x2); x++) {
var l = new Point(Math.toIntExact(x), Math.toIntExact(c.y1));
if (!all.add(l)) {
vis.add(l);
}
}
} else if ((c.x1 > c.x2 && c.y1 > c.y2) || (c.x1 < c.x2 && c.y1 < c.y2)) {
for (long x = 0; x <= Math.max(c.x1, c.x2) - Math.min(c.x1, c.x2); x++) {
var l = new Point(Math.toIntExact(Math.min(c.x1, c.x2) + x), Math.toIntExact(Math.min(c.y1, c.y2) + x));
if (!all.add(l)) {
vis.add(l);
}
}
} else if (c.x1 < c.x2 && c.y1 > c.y2) {
for (long x = 0; x <= Math.max(c.x1, c.x2) - Math.min(c.x1, c.x2); x++) {
var l = new Point(Math.toIntExact(c.x1 + x), Math.toIntExact(c.y1 - x));
if (!all.add(l)) {
vis.add(l);
}
}
} else if (c.x1 > c.x2 && c.y1 < c.y2) {
for (long x = 0; x <= Math.max(c.x1, c.x2) - Math.min(c.x1, c.x2); x++) {
var l = new Point(Math.toIntExact(c.x1 - x), Math.toIntExact(c.y1 + x));
if (!all.add(l)) {
vis.add(l);
}
}
} else throw new IllegalStateException("not covered " + c);
}
return vis.size();
}
public record Coords(long x1, long y1, long x2, long y2) {
}
}