day 5 part 2
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Ben Harris 2021-12-05 19:36:45 -05:00
parent 4d17d257e8
commit eec86d7fd1
2 changed files with 18 additions and 70 deletions

View File

@ -8,6 +8,7 @@ public class DayTests
[DataRow(typeof(Day02), "2272262", "2134882034")]
[DataRow(typeof(Day03), "3009600", "6940518")]
[DataRow(typeof(Day04), "8580", "9576")]
[DataRow(typeof(Day05), "7318", "19939")]
public void CheckAllDays(Type dayType, string part1, string part2)
{
var s = Stopwatch.StartNew();
@ -42,7 +43,7 @@ public class DayTests
[DataRow(typeof(Day02), "150", "900")]
[DataRow(typeof(Day03), "198", "230")]
[DataRow(typeof(Day04), "4512", "1924")]
[DataRow(typeof(Day05), "5", "")]
[DataRow(typeof(Day05), "5", "12")]
public void CheckTestInputs(Type dayType, string part1, string part2)
{
Day.UseTestInput = true;

View File

@ -1,82 +1,29 @@
using System.Drawing;
namespace aoc2021;
namespace aoc2021;
/// <summary>
/// Day 5: <see href="https://adventofcode.com/2021/day/5"/>
/// </summary>
public sealed class Day05 : Day
{
private readonly List<Line> _lines;
public Day05() : base(5, "Hydrothermal Venture")
{
_lines = Input.Select(l => new Line(l)).ToList();
}
private class Line
{
public int X1 { get; }
public int X2 { get; }
public int Y1 { get; }
public int Y2 { get; }
private int Solve(bool diagonals = false) =>
Input
.Where(s => !string.IsNullOrEmpty(s))
.Select(s => s.Split(" -> "))
.Select(a => a.Select(i => i.Split(',')).SelectMany(i => i.Select(int.Parse)).ToList())
.Where(t => diagonals || t[0] == t[2] || t[1] == t[3])
.SelectMany(t =>
Enumerable.Range(0, Math.Max(Math.Abs(t[0] - t[2]), Math.Abs(t[1] - t[3])) + 1)
.Select(i => (
t[0] > t[2] ? t[2] + i : t[0] < t[2] ? t[2] - i : t[2],
t[1] > t[3] ? t[3] + i : t[1] < t[3] ? t[3] - i : t[3])))
.GroupBy(k => k)
.Count(k => k.Count() > 1);
public readonly List<Point> AllPoints = new();
public Line(string line)
{
var s = line
.Split(" -> ")
.Select(i => i.Split(',').Select(int.Parse))
.SelectMany(i => i)
.ToList();
X1 = s[0];
X2 = s[1];
Y1 = s[2];
Y2 = s[3];
public override string Part1() => $"{Solve()}";
if (X1 == X2)
{
var minY = Math.Min(Y1, Y2);
var maxY = Math.Max(Y1, Y2);
for (var i = 0; i < maxY - minY; i++)
{
AllPoints.Add(new(minY + i, X1));
}
}
else if (Y1 == Y2)
{
var minX = Math.Min(X1, X2);
var maxX = Math.Max(X1, X2);
for (var i = 0; i < maxX - minX; i++)
{
AllPoints.Add(new(minX + i, Y1));
}
}
else
{
var oX = X1 < X2 ? 1 : -1;
var oY = Y1 < Y2 ? 1 : -1;
for (var i = 0; i < Math.Abs(X1 - X2); i++)
{
AllPoints.Add(new(X1 + i * oX, Y1 + i * oY));
}
}
}
}
public override string Part1()
{
var groups = _lines
.Where(l => l.X1 != l.X2 && l.Y1 != l.Y2)
.SelectMany(l => l.AllPoints)
.GroupBy(x => x);
return $"{groups.Count(g => g.Count() > 1)}";
}
public override string Part2() => "";
public override string Part2() => $"{Solve(diagonals: true)}";
}