-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay5.cs
More file actions
76 lines (68 loc) · 2.6 KB
/
Copy pathDay5.cs
File metadata and controls
76 lines (68 loc) · 2.6 KB
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
namespace Advent_of_Code_2022
{
internal class Day5 : ISolver
{
public string Title => "Supply Stacks";
public string PartOne(string input)
{
var (state, moves) = GetInitialState(input);
return MoveCrates(state, moves, moveTogether: false);
}
public string PartTwo(string input)
{
var (state, moves) = GetInitialState(input);
return MoveCrates(state, moves, moveTogether: true);
}
private (Dictionary<int, List<char>> state, string[] moves) GetInitialState(string input)
{
var sections = input.Split($"{Environment.NewLine}{Environment.NewLine}");
var crates = sections[0].Split('\n');
var state = new Dictionary<int, List<char>>();
foreach (var crateLine in crates)
{
for (int i = 0; i < crateLine.Length; i++)
{
char c = crateLine[i];
if (char.IsLetter(c))
{
int n = (i / 4) + 1;
if (!state.ContainsKey(n))
{
state[n] = new List<char>();
}
state[n].Add(c);
}
}
}
var moves = sections[1].Split('\n');
return (state, moves);
}
private static string MoveCrates(Dictionary<int, List<char>> state, string[] moves, bool moveTogether)
{
foreach (var move in moves)
{
var numberOfCrates = int.Parse(move.Split("move ")[1].Split(" ")[0]);
var from = int.Parse(move.Split("from ")[1].Split(" ")[0]);
var to = int.Parse(move.Split("to ")[1].Split(" ")[0]);
void moveCrates(int numberOfCratesToMoveAtOnce)
{
var cratesToMove = state[from].GetRange(0, numberOfCratesToMoveAtOnce);
state[from].RemoveRange(0, numberOfCratesToMoveAtOnce);
state[to].InsertRange(0, cratesToMove);
}
if (moveTogether)
{
moveCrates(numberOfCrates);
}
else
{
for (int i = 0; i < numberOfCrates; i++)
{
moveCrates(1);
}
}
}
return string.Join("", state.OrderBy(s => s.Key).Select(s => s.Value[0]));
}
}
}