-
Notifications
You must be signed in to change notification settings - Fork 0
/
AoC Day 09.m
51 lines (43 loc) · 1.37 KB
/
AoC Day 09.m
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
(* ::Package:: *)
(* ::Text:: *)
(*Written December 9th, 2022.*)
(*Import*)
day = 9;
inputPath = FileNameJoin[{NotebookDirectory[], "Day" <> ToString[day] <> "Input.txt"}];
toExpression[inputText_] :=
Map[
If[! IntegerQ[#] \[And]
StringMatchQ[#,
Alternatives["+", "-", ""] ~~ DigitCharacter ..],
ToExpression[#], #] &,
inputText,
{Depth[inputText] - 1, Depth[inputText]}];
input = toExpression[Import[inputPath, "Table"]];
(*Parts 1 & 2*)
position = Table[{0, 0}, {i, 10}];
part1Positions = {};
part2Positions = {};
Do[
Which[
line[[1]] == "R", position[[1]] += {1, 0},
line[[1]] == "L", position[[1]] += {-1, 0},
line[[1]] == "U", position[[1]] += {0, 1},
line[[1]] == "D", position[[1]] += {0, -1}];
Do[
If[Max[Abs[position[[i - 1]] - position[[i]]]] >= 2,
If[Min[Abs[position[[i - 1]] - position[[i]]]] == 0,
inc =
SelectFirst[{{1, 0}, {-1, 0}, {0, 1}, {0, -1}},
Max[Abs[position[[i - 1]] - (# + position[[i]])]] == 1 &],
inc =
SelectFirst[{{1, 1}, {-1, 1}, {1, -1}, {-1, -1}},
Max[Abs[position[[i - 1]] - (# + position[[i]])]] == 1 &]
];
position[[i]] += inc;
],
{i, 2, 10}];
AppendTo[part1Positions, position[[2]]];
AppendTo[part2Positions, position[[-1]]],
{line, input},
{count, line[[2]]}];
Length /@ {DeleteDuplicates[part1Positions], DeleteDuplicates[part2Positions]}