1
1
package com .sbaars .adventofcode .year15 .days ;
2
2
3
3
import com .sbaars .adventofcode .common .Direction ;
4
+ import com .sbaars .adventofcode .common .location .Loc ;
4
5
import com .sbaars .adventofcode .common .location .MutableLoc ;
5
6
import com .sbaars .adventofcode .year15 .Day2015 ;
6
7
8
+ import java .util .HashSet ;
9
+ import java .util .Set ;
10
+ import java .util .stream .Stream ;
11
+
7
12
import static com .sbaars .adventofcode .common .Direction .*;
8
13
import static com .sbaars .adventofcode .util .AoCUtils .zipWithIndex ;
9
14
@@ -18,26 +23,41 @@ public static void main(String[] args) {
18
23
19
24
@ Override
20
25
public Object part1 () {
21
- MutableLoc loc = new MutableLoc ();
22
- return day ()
23
- .chars ()
24
- .mapToObj (c -> charToDir ((char ) c ))
25
- .map (d -> loc .set (d .move (loc .get ())))
26
- .distinct ()
27
- .count ();
26
+ return countVisitedHouses (dayStream ()
27
+ .flatMapToInt (String ::chars )
28
+ .mapToObj (c -> charToDir ((char ) c )));
28
29
}
29
30
30
31
@ Override
31
32
public Object part2 () {
33
+ return countVisitedHousesWithRobo (dayStream ()
34
+ .flatMapToInt (String ::chars )
35
+ .mapToObj (c -> charToDir ((char ) c )));
36
+ }
37
+
38
+ private long countVisitedHouses (Stream <Direction > directions ) {
39
+ MutableLoc loc = new MutableLoc ();
40
+ Set <Loc > visited = new HashSet <>();
41
+ visited .add (loc .get ());
42
+ directions .forEach (d -> visited .add (loc .set (d .move (loc .get ()))));
43
+ return visited .size ();
44
+ }
45
+
46
+ private long countVisitedHousesWithRobo (Stream <Direction > directions ) {
32
47
MutableLoc santa = new MutableLoc ();
33
48
MutableLoc robo = new MutableLoc ();
34
- return zipWithIndex (day ().chars ().mapToObj (c -> charToDir ((char ) c )))
35
- .map (d -> d .i () % 2 == 0 ? santa .set (d .e ().move (santa .get ())) : robo .set (d .e ().move (robo .get ())))
36
- .distinct ()
37
- .count ();
49
+ Set <Loc > visited = new HashSet <>();
50
+ visited .add (santa .get ());
51
+
52
+ zipWithIndex (directions )
53
+ .forEach (d -> {
54
+ var current = d .i () % 2 == 0 ? santa : robo ;
55
+ visited .add (current .set (d .e ().move (current .get ())));
56
+ });
57
+ return visited .size ();
38
58
}
39
59
40
- public Direction charToDir (char c ) {
60
+ private static Direction charToDir (char c ) {
41
61
return switch (c ) {
42
62
case '^' -> NORTH ;
43
63
case '>' -> EAST ;
0 commit comments