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.
This commit is contained in:
2022-12-15 16:13:36 -06:00
parent 70758cf4a9
commit fdf621b58d

View File

@ -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<ivec2> emptySpace = new();
HashSet<long> 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}";
}