about summary refs log tree commit diff
path: root/Day13.cs
blob: 4dff71240c7579a8e0b16c503690ef787283e828 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Collections.Generic;
using System.Linq;
using aoc2019.lib;

namespace aoc2019
{
    internal sealed class Day13 : Day
    {
        private readonly Dictionary<(int x, int y), int> board;

        private readonly IntCodeVM vm;

        public Day13() : base(13, "Care Package")
        {
            vm = new IntCodeVM(Input.First());
            board = new Dictionary<(int, int), int>();
        }

        private void UpdateTiles(IEnumerable<long> queue)
        {
            var input = queue.Select(i => (int) i).ToList();

            for (var i = 0; i < input.Count - 2; i += 3)
            {
                var x = input[i];
                var y = input[i + 1];
                var val = input[i + 2];

                if (board.ContainsKey((x, y)))
                    board[(x, y)] = val;
                else
                    board.Add((x, y), val);
            }
        }

        private void PrintBoard()
        {
            foreach (var ((x, y), value) in board)
            {
                if (x < 0 || y < 0) continue;
                Console.SetCursorPosition(x, y);
                Console.Write(value switch
                {
                    0 => " ",
                    1 => "|",
                    2 => "B",
                    3 => "_",
                    4 => ".",
                    _ => value
                });
            }
        }

        protected override string Part1()
        {
            vm.Reset();
            vm.Run();
            return $"{vm.output.Where((v, i) => (i + 1) % 3 == 0 && v == 2).Count()}";
        }

        protected override string Part2()
        {
            vm.Reset();
            vm.memory[0] = 2;
            var printBoard = false;
            var gameTicks = 0;
            if (printBoard) Console.Clear();

            var haltType = IntCodeVM.HaltType.Waiting;
            while (haltType == IntCodeVM.HaltType.Waiting)
            {
                haltType = vm.Run();
                UpdateTiles(vm.output);

                var (ball, _) = board.First(t => t.Value == 4).Key;
                var (paddle, _) = board.First(t => t.Value == 3).Key;
                vm.AddInput(ball > paddle ? 1 : ball < paddle ? -1 : 0);

                gameTicks++;
                if (printBoard) PrintBoard();
            }

            return $"after {gameTicks} moves, the score is: {board[(-1, 0)]}";
        }
    }
}