Skip to content

Commit b875799

Browse files
committed
2024/06 speedup
1 parent 35d07f6 commit b875799

File tree

1 file changed

+7
-14
lines changed

1 file changed

+7
-14
lines changed

2024/Day06/Solution.cs

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@ namespace AdventOfCode.Y2024.Day06;
55
using System.Collections.Immutable;
66
using System.Linq;
77
using System.Numerics;
8-
9-
using Map = System.Collections.Generic.Dictionary<System.Numerics.Complex, char>;
8+
using Map = System.Collections.Immutable.ImmutableDictionary<System.Numerics.Complex, char>;
109

1110
[ProblemName("Guard Gallivant")]
1211
class Solution : Solver {
@@ -21,17 +20,11 @@ public object PartOne(string input) {
2120

2221
public object PartTwo(string input) {
2322
var (map, start) = Parse(input);
24-
var positions = Walk(map, start).positions;
25-
var loops = 0;
26-
// simply try a blocker in each locations visited by the guard and count the loops
27-
foreach (var block in positions.Where(pos => map[pos] == '.')) {
28-
map[block] = '#';
29-
if (Walk(map, start).isLoop) {
30-
loops++;
31-
}
32-
map[block] = '.';
33-
}
34-
return loops;
23+
// try a blocker in each locations visited by the guard counting the loops
24+
return Walk(map, start).positions
25+
.AsParallel()
26+
.Count(pos => Walk(map.SetItem(pos, '#'), start).isLoop);
27+
3528
}
3629

3730
// returns the positions visited when starting from 'pos', isLoop is set if the
@@ -61,7 +54,7 @@ public object PartTwo(string input) {
6154
from y in Enumerable.Range(0, lines.Length)
6255
from x in Enumerable.Range(0, lines[0].Length)
6356
select new KeyValuePair<Complex, char>(-Up * y + x, lines[y][x])
64-
).ToDictionary();
57+
).ToImmutableDictionary();
6558

6659
var start = map.First(x => x.Value == '^').Key;
6760

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy