-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConsoleVM.cs
81 lines (69 loc) · 2.77 KB
/
ConsoleVM.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.RegularExpressions;
namespace AdventOfCode2020
{
internal static class ConsoleVM
{
private static readonly Regex ParseRegex = new("(?<operation>\\w+) (?<argument>(\\+|-)\\d+)");
private static Operation OperationFromString(string value) => Enum.Parse<Operation>(value, true);
[SuppressMessage("ReSharper", "ReturnTypeCanBeEnumerable.Global",
Justification = "Indexed access required implicit")]
internal static IList<Instruction> Parse(IEnumerable<string> input)
=> input.Select(line =>
{
var matchGroups = ParseRegex.Match(line).Groups;
return new Instruction(OperationFromString(matchGroups["operation"].Value),
long.Parse(matchGroups["argument"].Value));
}).ToList();
[SuppressMessage("ReSharper", "ParameterTypeCanBeEnumerable.Global",
Justification = "Indexed access required implicit")]
internal static Registers Step(IList<Instruction> instructions, Registers registers)
{
(int pc, long acc) = registers;
var instruction = instructions.ElementAtOrDefault(pc) ??
throw new InvalidOperationException($"No instruction at pc '{pc}'");
switch (instruction.Operation)
{
case Operation.ACC:
acc += instruction.Argument;
goto case Operation.NOP;
case Operation.JMP:
pc += (int) instruction.Argument;
break;
case Operation.NOP:
pc++;
break;
default:
throw new ArgumentOutOfRangeException(nameof(instruction), "Invalid Instruction");
}
return new Registers(pc, acc);
}
[SuppressMessage("ReSharper", "InconsistentNaming")]
internal enum Operation
{
ACC,
JMP,
NOP,
}
internal class Instruction
{
public Instruction(Operation operation, long argument) => (Operation, Argument) = (operation, argument);
public Operation Operation { get; set; }
public long Argument { get; }
}
[SuppressMessage("ReSharper", "InconsistentNaming")]
internal class Registers
{
public Registers()
{
}
public Registers(int pc, long acc) => (PC, ACC) = (pc, acc);
public int PC { get; }
public long ACC { get; }
public void Deconstruct(out int pc, out long acc) => (pc, acc) = (PC, ACC);
}
}
}