From c292bd45c6417127d851ebdf08a68f9e7928e275 Mon Sep 17 00:00:00 2001 From: Parnic Date: Sun, 12 Dec 2021 10:57:29 -0600 Subject: [PATCH] 3.4x speedup on Day 12 First round of the lowest of low-hanging fruits to get day 12 runtime from ~1s to ~280ms on my machine in Release. Still not happy with 280ms, so I will probably keep digging. --- src/12.cs | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/src/12.cs b/src/12.cs index 50c0562..9171eda 100644 --- a/src/12.cs +++ b/src/12.cs @@ -20,8 +20,14 @@ internal class Day12 paths[points[1]] = new List(); } - paths[points[0]].Add(points[1]); - paths[points[1]].Add(points[0]); + if (points[0] != "end" && points[1] != "start") + { + paths[points[0]].Add(points[1]); + } + if (points[1] != "end" && points[0] != "start") + { + paths[points[1]].Add(points[0]); + } } Part1(paths); Part2(paths); @@ -38,28 +44,24 @@ internal class Day12 Logger.Log($"part1: {validPaths.Count}"); } - private static void FindPaths(Dictionary> paths, List> routes, List currRoute, bool canVisitSmallCaveTwice) + private static void FindPaths(Dictionary> paths, List> routes, List currRoute, bool canVisitSmallCaveTwice, bool hasDoubledCave = false) { //Logger.Log($"Current path: {string.Join(',', currRoute)}"); var curr = currRoute.Last(); foreach (var next in paths[curr]) { //Logger.Log($" Evaluating next: {next}"); - if (next == "start") - { - //Logger.Log($" is start, skipping"); - continue; - } if (next != "end" && next.ToLower() == next && currRoute.Contains(next)) { - if (!canVisitSmallCaveTwice) + if (!canVisitSmallCaveTwice || hasDoubledCave) { //Logger.Log($" is already-visited small cave, skipping"); continue; } - else if (currRoute.Any(x => x.ToLower() == x && currRoute.Count(y => x == y) == 2)) + else if (currRoute.Any(x => x[0] >= 'a' && x[0] <= 'z' && currRoute.Count(y => x == y) == 2)) { //Logger.Log($" is already-visited small cave and we have already been to another one twice, skipping"); + hasDoubledCave = true; continue; } } @@ -68,11 +70,11 @@ internal class Day12 if (next == "end") { //Logger.Log($" is end, so adding {string.Join(',', currRoute)} to valid paths"); - routes.Add(currRoute); + routes.Add(new List(currRoute)); } else { - FindPaths(paths, routes, new List(currRoute), canVisitSmallCaveTwice); + FindPaths(paths, routes, currRoute, canVisitSmallCaveTwice, hasDoubledCave); } currRoute.RemoveAt(currRoute.Count - 1);