-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4.mojo
105 lines (93 loc) · 2.57 KB
/
4.mojo
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
fn search(data: List[String], r: Int, c: Int, dr: Int, dc: Int) raises:
target = String("XMAS")
for i in range(len(target)):
x = target[i]
rr = r + i * dr
cc = c + i * dc
if not (0 <= rr < len(data) and 0 <= cc < len(data[0])):
raise Error()
if not data[rr][cc] == x:
raise Error()
fn search_mas(data: List[String], r: Int, c: Int, dr: Int, dc: Int) raises:
target = String("MAS")
parity = List[Int](1, -1)
succeeded = False
for p in parity:
pp = p[]
ddr = pp * dr
ddc = pp * dc
rr = r - ddr
cc = c - ddc
failed = False
for i in range(len(target)):
x = target[i]
rrr = rr + i * ddr
ccc = cc + i * ddc
if not (0 <= rrr < len(data) and 0 <= ccc < len(data[0])):
failed = True
continue
if not data[rrr][ccc] == x:
failed = True
if not failed:
succeeded = True
if not succeeded:
raise Error()
fn part_one() raises:
data = List[String]()
with open("./inputs/4.input", "r") as f:
lines = f.read().splitlines(keepends=False)
for line in lines:
# row = List[String]()
# for c in range(line):
if line[]:
data.append(line[])
height = len(data)
width = len(data[0])
DIR_R = List[Int](
-1,
-1,
-1,
0,
0,
1,
1,
1,
)
DIR_C = List[Int](-1, 0, 1, -1, 1, -1, 0, 1)
yay = 0
for r in range(height):
for c in range(width):
for j in range(len(DIR_R)):
dr = DIR_R[j]
dc = DIR_C[j]
# print(r, c, dr, dc)
try:
search(data, r, c, dr, dc)
yay += 1
except:
pass
print(yay)
fn part_two() raises:
data = List[String]()
with open("./inputs/4.input", "r") as f:
lines = f.read().splitlines(keepends=False)
for line in lines:
# row = List[String]()
# for c in range(line):
if line[]:
data.append(line[])
height = len(data)
width = len(data[0])
yay = 0
for r in range(height):
for c in range(width):
try:
search_mas(data, r, c, 1, 1)
search_mas(data, r, c, -1, 1)
yay += 1
except:
pass
print(yay)
fn main() raises:
part_one()
part_two()