-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAoC Day 21.m
78 lines (65 loc) · 2.26 KB
/
AoC Day 21.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
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
(* ::Package:: *)
(* ::Text:: *)
(*Written December 21st, 2022.*)
(*Import*)
day = 21;
inputPath = FileNameJoin[{NotebookDirectory[], "Day" <> ToString[day] <> "Input.txt"}];
toExpression[inputText_] :=
Map[
If[! IntegerQ[#] &&
StringMatchQ[#,
Alternatives["+", "-", ""] ~~ DigitCharacter ..],
ToExpression[#], #] &,
inputText,
{Depth[inputText] - 1, Depth[inputText]}];
input = toExpression[
StringSplit[#, Alternatives[",", " ", ":", "."]] & /@
StringSplit[Import[inputPath], "\n"]];
input = Select[#, # =!= "" &] & /@ input;
(*Part 1*)
constants = Select[input, Length[#] == 2 \[And] IntegerQ[#[[2]]] &];
ClearAll@memory;
Do[memory[c[[1]]] = c[[2]], {c, constants}];
operations =
Select[input, ! (Length[#] == 2 \[And] IntegerQ[#[[2]]]) &];
g = Graph[Join[
Flatten[{#[[2]] -> #[[1]], #[[4]] -> #[[1]]} & /@ operations],
#[[2]] -> #[[1]] & /@ constants]];
ClearAll@getOp;
Do[getOp[p[[1]]] = p, {p, operations}];
priority =
Select[TopologicalSort[g], MemberQ[operations[[;; , 1]], #] &];
Do[
memory[line[[1]]] =
Which[
line[[3]] == "+", Plus[memory[line[[2]]], memory[line[[4]]]],
line[[3]] == "-", Plus[memory[line[[2]]], -memory[line[[4]]]],
line[[3]] == "*", Times[memory[line[[2]]], memory[line[[4]]]],
line[[3]] == "/", Times[memory[line[[2]]], 1/memory[line[[4]]]]
],
{line, getOp /@ priority}];
memory["root"]
(*Part 2*)
constants = Select[input, Length[#] == 2 \[And] IntegerQ[#[[2]]] &];
ClearAll@memory;
Do[memory[c[[1]]] = c[[2]], {c, constants}];
memory["humn"] = humn;
operations =
Select[input, ! (Length[#] == 2 \[And] IntegerQ[#[[2]]]) &];
g = Graph[Join[
Flatten[{#[[2]] -> #[[1]], #[[4]] -> #[[1]]} & /@ operations],
#[[2]] -> #[[1]] & /@ constants]];
ClearAll@getOp;
Do[getOp[p[[1]]] = p, {p, operations}];
priority =
Select[TopologicalSort[g], MemberQ[operations[[;; , 1]], #] &];
Do[
memory[line[[1]]] =
Which[
line[[3]] == "+", Plus[memory[line[[2]]], memory[line[[4]]]],
line[[3]] == "-", Plus[memory[line[[2]]], -memory[line[[4]]]],
line[[3]] == "*", Times[memory[line[[2]]], memory[line[[4]]]],
line[[3]] == "/", Times[memory[line[[2]]], 1/memory[line[[4]]]]
],
{line, getOp /@ priority}];
Solve[memory[#[[2]]] == memory[#[[4]]] &@getOp["root"], humn]