aoc2019/Day11.cs

114 lines
3.1 KiB
C#
Raw Normal View History

2019-12-11 22:58:48 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using aoc2019.lib;
2019-12-11 22:58:48 +00:00
namespace aoc2019
{
2020-12-02 04:50:35 +00:00
internal sealed class Day11 : Day
2019-12-11 22:58:48 +00:00
{
2019-12-12 04:47:39 +00:00
private readonly IntCodeVM vm;
private Direction heading;
private long x, y;
2019-12-11 22:58:48 +00:00
public Day11()
{
vm = new IntCodeVM(Input.First());
}
public override int DayNumber => 11;
2019-12-11 22:58:48 +00:00
2019-12-12 04:47:39 +00:00
private void Move()
2019-12-11 22:58:48 +00:00
{
2019-12-12 04:47:39 +00:00
switch (heading)
2019-12-11 22:58:48 +00:00
{
case Direction.Up:
y++;
break;
case Direction.Down:
y--;
break;
case Direction.Left:
x--;
break;
case Direction.Right:
x++;
break;
}
;
2019-12-11 22:58:48 +00:00
}
private void Turn(long direction)
{
switch (heading)
{
case Direction.Up:
heading = direction == 0 ? Direction.Left : Direction.Right;
break;
case Direction.Down:
heading = direction == 0 ? Direction.Right : Direction.Left;
break;
case Direction.Left:
heading = direction == 0 ? Direction.Down : Direction.Up;
break;
case Direction.Right:
heading = direction == 0 ? Direction.Up : Direction.Down;
break;
2019-12-11 22:58:48 +00:00
}
2019-12-12 04:47:39 +00:00
Move();
2019-12-11 22:58:48 +00:00
}
2019-12-12 04:47:39 +00:00
private Dictionary<(long x, long y), long> PaintShip(int initialVal)
2019-12-11 22:58:48 +00:00
{
2019-12-12 04:47:39 +00:00
var map = new Dictionary<(long, long), long>();
2019-12-11 22:58:48 +00:00
vm.Reset();
2019-12-12 04:47:39 +00:00
heading = Direction.Up;
x = 0;
y = 0;
2019-12-12 04:47:39 +00:00
map[(x, y)] = initialVal;
var haltType = IntCodeVM.HaltType.Waiting;
while (haltType == IntCodeVM.HaltType.Waiting)
2019-12-11 22:58:48 +00:00
{
2019-12-12 04:47:39 +00:00
haltType = vm.Run(map.GetValueOrDefault((x, y)));
map[(x, y)] = vm.Result;
Turn(vm.Result);
2019-12-11 22:58:48 +00:00
}
2019-12-12 04:47:39 +00:00
return map;
}
2020-12-02 06:58:54 +00:00
protected override string Part1()
2019-12-12 04:47:39 +00:00
{
return $"{PaintShip(0).Count}";
2019-12-11 22:58:48 +00:00
}
2020-12-02 06:58:54 +00:00
protected override string Part2()
2019-12-11 22:58:48 +00:00
{
2019-12-12 04:47:39 +00:00
var map = PaintShip(1);
var minX = (int) map.Keys.Select(x => x.x).Min();
var maxX = (int) map.Keys.Select(x => x.x).Max();
var minY = (int) map.Keys.Select(x => x.y).Min();
var maxY = (int) map.Keys.Select(x => x.y).Max();
2019-12-12 04:47:39 +00:00
return Enumerable.Range(minY, maxY - minY + 1)
.Select(y =>
Enumerable.Range(minX, maxX - minX + 1)
.Select(x => map.GetValueOrDefault((x, y)) == 0 ? ' ' : '#')
.ToDelimitedString()
2019-12-12 04:47:39 +00:00
)
.Reverse()
.ToDelimitedString(Environment.NewLine);
2019-12-11 22:58:48 +00:00
}
private enum Direction
{
Up,
Down,
Left,
Right
}
2019-12-11 22:58:48 +00:00
}
}