Day 5 solution

A Deep Copy and a double-ended queue would have made this day much easier. I should add those. (Having trouble finding a generic deep copy that works in .net 6, though...I opted to rewrite my original List<List<char>> solution into List<string> in lieu of a deep copy so I wouldn't have to parse the input all over again.)
This commit is contained in:
2022-12-04 23:46:24 -06:00
parent 4b51ff9970
commit b9161e4b42
4 changed files with 623 additions and 500 deletions

View File

@ -79,6 +79,8 @@
<EmbeddedResource Include="inputs\03a.txt" />
<None Remove="inputs\04a.txt" />
<EmbeddedResource Include="inputs\04a.txt" />
<None Remove="inputs\05a.txt" />
<EmbeddedResource Include="inputs\05a.txt" />
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

9
inputs/05a.txt Normal file
View File

@ -0,0 +1,9 @@
 [D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2

100
src/05.cs Normal file
View File

@ -0,0 +1,100 @@
using System.Text;
namespace aoc2022;
internal class Day05 : Day
{
struct Instruction
{
public int Num;
public int From;
public int To;
}
private readonly List<string> defaultLines = new();
private readonly List<Instruction> instructions = new();
internal override void Parse()
{
int state = 0;
foreach (var line in Util.ReadAllLines("05"))
{
if (state == 0)
{
if (line.Contains('['))
{
int col = 0;
for (int i = 1; i < line.Length; i += 4)
{
if (line[i] != ' ')
{
while (defaultLines.Count <= col)
{
defaultLines.Add(string.Empty);
}
defaultLines[col] += line[i];
}
col++;
}
}
else if (string.IsNullOrEmpty(line))
{
state = 1;
}
continue;
}
var inst = line.Split(' ');
instructions.Add(new Instruction()
{
Num = int.Parse(inst[1]),
From = int.Parse(inst[3]) - 1,
To = int.Parse(inst[5]) - 1,
});
}
}
internal override string Part1()
{
List<string> lines = new(defaultLines);
foreach (var inst in instructions)
{
for (int i = 0; i < inst.Num; i++)
{
var val = lines[inst.From].First();
lines[inst.From] = lines[inst.From][1..];
lines[inst.To] = lines[inst.To].Insert(0, val.ToString());
}
}
StringBuilder sb = new();
foreach (var line in lines)
{
sb.Append(line.First());
}
return $"CrateMover9000 final order: <+white>{sb}";
}
internal override string Part2()
{
List<string> lines = new(defaultLines);
foreach (var inst in instructions)
{
for (int i = 0; i < inst.Num; i++)
{
var val = lines[inst.From].First();
lines[inst.From] = lines[inst.From][1..];
lines[inst.To] = lines[inst.To].Insert(i, val.ToString());
}
}
StringBuilder sb = new();
foreach (var line in lines)
{
sb.Append(line.First());
}
return $"CrateMover9001 final order: <+white>{sb}";
}
}