aoc2021/aoc2021/Day13.cs

75 lines
2.0 KiB
C#
Raw Permalink Normal View History

2021-12-13 06:20:33 +00:00
using MoreLinq;
namespace aoc2021;
/// <summary>
/// Day 13: <see href="https://adventofcode.com/2021/day/13"/>
/// </summary>
public sealed class Day13 : Day
{
2021-12-13 06:38:11 +00:00
private List<(int x, int y)> _dots;
2021-12-13 06:20:33 +00:00
private readonly List<(char axis, int index)> _folds;
public Day13() : base(13, "Transparent Origami")
{
var s = Input.Split("").ToList();
2021-12-13 06:38:11 +00:00
_dots = s[0].Select(p =>
2021-12-13 06:20:33 +00:00
{
var i = p.Split(',', 2).Select(int.Parse).ToList();
return (i[0], i[1]);
}).ToList();
_folds = s[1].Select(p => p.Split(' ').Skip(2).First()).Select(p =>
{
var i = p.Split('=', 2);
return (i[0][0], int.Parse(i[1]));
}).ToList();
}
private static List<(int x, int y)> DoFold(List<(int x, int y)> grid, char axis, int at)
{
List<(int, int)> result = new();
switch (axis)
{
case 'x':
2021-12-13 06:38:11 +00:00
foreach (var (x, y) in grid) result.Add((x > at ? 2 * at - x : x, y));
2021-12-13 06:20:33 +00:00
break;
case 'y':
2021-12-13 06:38:11 +00:00
foreach (var (x, y) in grid) result.Add((x, y > at ? 2 * at - y : y));
2021-12-13 06:20:33 +00:00
break;
2021-12-13 06:38:11 +00:00
default: throw new ArgumentException("invalid fold axis", nameof(axis));
2021-12-13 06:20:33 +00:00
}
return result.Distinct().ToList();
}
private string PrintGrid()
{
2021-12-13 06:38:11 +00:00
var xMax = _dots.Max(g => g.x);
var yMax = _dots.Max(g => g.y);
2021-12-13 06:20:33 +00:00
var s = new StringBuilder();
for (var y = 0; y <= yMax; y++)
{
for (var x = 0; x <= xMax; x++)
2021-12-13 06:38:11 +00:00
s.Append(_dots.Contains((x, y)) ? "█" : "▒");
2021-12-13 06:20:33 +00:00
s.AppendLine();
}
return s.ToString();
}
2021-12-13 06:38:11 +00:00
public override object Part1() =>
DoFold(_dots, _folds[0].axis, _folds[0].index).Count;
2021-12-13 06:20:33 +00:00
public override object Part2()
{
foreach (var (axis, at) in _folds)
2021-12-13 06:38:11 +00:00
_dots = DoFold(_dots, axis, at);
2021-12-13 06:20:33 +00:00
return Environment.NewLine + PrintGrid();
}
2021-12-13 06:38:11 +00:00
}