-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThrusterPowerSystem.cs
86 lines (80 loc) · 2.37 KB
/
ThrusterPowerSystem.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
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AdventOfCode.Year2019.Day07;
public class ThrusterPowerSystem
{
private int StartPower { get; }
private IList<IntcodeMachine> Amplifiers { get; }
public ThrusterPowerSystem(int[] ampProgram, int nofAmplifiers, int startPower)
{
Amplifiers = Enumerable.Range(0, nofAmplifiers).Select(_ => new IntcodeMachine(ampProgram)).ToArray();
StartPower = startPower;
}
public void Reset()
{
foreach (IntcodeMachine amplifier in Amplifiers)
{
amplifier.ResetMachine();
}
}
public int GetThrusterPower(IReadOnlyList<int> phaseSettings)
{
if (phaseSettings is null)
{
throw new ArgumentNullException(nameof(phaseSettings));
}
if (phaseSettings.Count != Amplifiers.Count)
{
throw new ArgumentException("The length of the phase settings array should match the number of amplifiers.");
}
int power = 0;
for (int i = 0; i < Amplifiers.Count; i++)
{
Amplifiers[i].ResetMachine();
Amplifiers[i].InputValues = new List<int> { phaseSettings[i], power };
Amplifiers[i].OutputStream = new MemoryStream();
_ = Amplifiers[i].Run();
_ = Amplifiers[i].OutputStream.Seek(0, SeekOrigin.Begin);
using StreamReader reader = new(Amplifiers[i].OutputStream);
power = int.Parse(reader.ReadToEnd());
}
return power;
}
public int GetRecurrentThrusterPower(IReadOnlyList<int> phaseSettings, bool resetAtStart = false)
{
if (phaseSettings is null)
{
throw new ArgumentNullException(nameof(phaseSettings));
}
if (phaseSettings.Count != Amplifiers.Count)
{
throw new ArgumentException("The length of the phase settings array should match the number of amplifiers.");
}
if (resetAtStart)
{
Reset();
}
int[] lastSignals = new int[Amplifiers.Count];
for (int i = 0; i < Amplifiers.Count; i++)
{
Amplifiers[i].InputValues = new List<int> { phaseSettings[i] };
}
int power = StartPower;
for (int i = 0; ; i = (i + 1) % Amplifiers.Count)
{
Amplifiers[i].InputValues.Add(power);
Amplifiers[i].OutputStream = new MemoryStream();
bool finished = Amplifiers[i].Run(breakOnOutputWritten: true);
if (finished)
{
return lastSignals[^1];
}
_ = Amplifiers[i].OutputStream.Seek(0, SeekOrigin.Begin);
using StreamReader reader = new(Amplifiers[i].OutputStream);
power = int.Parse(reader.ReadToEnd());
lastSignals[i] = power;
}
}
}