-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAoC Day 14.m
67 lines (55 loc) · 1.49 KB
/
AoC Day 14.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
(* ::Package:: *)
(* ::Text:: *)
(*Written December 14th, 2022.*)
(*Import*)
day = 14;
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[
StringSplit[#, {",", " -> "}] & /@
StringSplit[Import[inputPath], {"\n"}]];
input = Partition[#, 2] & /@ input;
(*Setup*)
line[{start_, end_}] :=
If[start[[1]] != end[[1]],
Table[{x, start[[2]]}, {x, start[[1]], end[[1]],
Sign[end[[1]] - start[[1]]]}],
Table[{start[[1]], y}, {y, start[[2]], end[[2]],
Sign[end[[2]] - start[[2]]]}]];
rockPositions = DeleteDuplicates[
Flatten[Table[
line /@ Partition[l, 2, 1],
{l, input}], 2]];
depth = Max[rockPositions[[;; , 2]]];
ClearAll@map;
map[{x_, y_}] := 0;
Do[map[r] = 1, {r, rockPositions}];
generateSand[] :=
Module[
{pos = {500, 0}, falling = True},
While[falling,
If[pos[[2]] == depth + 1, Return[pos, Module]];
If[map[pos + #] == 0, pos += #; Continue[]] & /@
{{0,
1}, {-1, 1}, {1, 1}};
falling = False;
];
Return[pos]
];
(*Parts 1 & 2*)
sand = {0, 0};
count = 0;
part1 = {False, 0};
While[sand != {500, 0},
sand = generateSand[];
If[sand[[2]] >= depth \[And] ! part1[[1]], part1 = {True, count}];
map[sand] = 2;
count += 1];
{part1[[2]], count}