From fdf621b58d5ed46c157f57c10d123f708db63ff7 Mon Sep 17 00:00:00 2001 From: Parnic Date: Thu, 15 Dec 2022 16:13:36 -0600 Subject: [PATCH] 10x speedup on part 1 Mostly from not testing and adding each individual vector, just the x component we care about. Some of the improvement came from setting capacity on the hash set up front. I could get even better if I was smarter about computing ranges of numbers rather than this dumb approach of putting each number into a hashset to function as a union/intersection surrogate. --- src/15.cs | 35 ++++++++--------------------------- 1 file changed, 8 insertions(+), 27 deletions(-) diff --git a/src/15.cs b/src/15.cs index fd8d526..28731a1 100644 --- a/src/15.cs +++ b/src/15.cs @@ -1,6 +1,7 @@ using System.Drawing; using System.Text.RegularExpressions; using aoc2022.Util; +using Math = System.Math; namespace aoc2022; @@ -44,45 +45,25 @@ internal class Day15 : Day internal override string Part1() { int interestedY = 2000000; - HashSet emptySpace = new(); + HashSet emptySpace = new(10_000_000); for (int i = 0; i < knownSensors.Count; i++) { var s = knownSensors[i]; var b = knownBeacons[i]; var dist = s.ManhattanDistanceTo(b); - for (int j = 0; ; j++) + var yDist = Math.Abs(interestedY - s.y); + var xWidth = dist - yDist; + if (xWidth >= 0) { - var testVec = new ivec2(s.x + j, interestedY); - if (testVec.ManhattanDistanceTo(s) <= dist) + for (long j = s.x - xWidth; j <= s.x + xWidth; j++) { - if (!knownBeacons.Contains(testVec)) - { - emptySpace.Add(testVec); - } - } - else - { - break; - } - } - for (int j = 0; ; j++) - { - var testVec = new ivec2(s.x - j, interestedY); - if (testVec.ManhattanDistanceTo(s) <= dist) - { - if (!knownBeacons.Contains(testVec)) - { - emptySpace.Add(testVec); - } - } - else - { - break; + emptySpace.Add(j); } } } + knownBeacons.Where(b => b.y == interestedY).ForEach(b => emptySpace.Remove(b.x)); return $"Empty spaces at y={interestedY:N0}: <+white>{emptySpace.Count}"; }