-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
188 lines (153 loc) · 6.54 KB
/
main.py
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
"""
Solution in pure TensorFlow to the puzzle
https://adventofcode.com/2022/day/11
of the Advent of Code 2022.
"""
import sys
from pathlib import Path
import tensorflow as tf
def main(input_path: Path) -> int:
"""entrypoint"""
dataset = tf.data.TextLineDataset(input_path.as_posix())
dataset = dataset.concatenate(tf.data.Dataset.from_tensors([""]))
monkey = tf.Variable(["", "", "", "", "", ""], dtype=tf.string)
monkey_id = tf.Variable(-1)
pos = tf.Variable(0)
initial_state = tf.constant(["", "", "", "", "", ""])
def init(old_state, line):
if tf.equal(line, ""):
monkey.assign(old_state, use_locking=True)
pos.assign(0)
return initial_state, True
if tf.strings.regex_full_match(line, r"^Monkey \d*:$"):
items = tf.strings.split(tf.strings.split([line], " ")[0][1], ":")[0]
updates = [items]
elif tf.equal(pos, 1):
items = tf.strings.strip(tf.strings.split([line], ":")[0][1])
updates = [items]
elif tf.equal(pos, 2):
op = tf.strings.strip(tf.strings.split([line], "="))[0][1]
updates = [op]
elif tf.equal(pos, 3):
divisible_by = tf.strings.strip(tf.strings.split([line], " "))[0][-1]
updates = [divisible_by]
else: # if tf.reduce_any([tf.equal(pos, 4), tf.equal(pos, 5)]):
monkey_dest = tf.strings.strip(tf.strings.split([line], " "))[0][-1]
updates = [monkey_dest]
indices = tf.reshape(pos, (1, 1))
new_state = tf.tensor_scatter_nd_update(old_state, indices, updates)
pos.assign_add(1)
return new_state, False
dataset = dataset.scan(initial_state, init)
monkey_count = tf.Variable(0)
for monkey_ready in dataset:
if monkey_ready:
# tf.print(monkey)
monkey.assign(tf.zeros_like(monkey))
monkey_count.assign_add(1)
inspected_count = tf.Variable(tf.zeros((monkey_count), tf.int64))
part = tf.Variable(1)
@tf.function
def apply_operation(worry_level, op):
op = tf.strings.split([op], " ")[0] # lhs, op, rhs
ret = tf.constant(0, tf.int64)
# lhs always = "old"
if tf.strings.regex_full_match(op[2], r"^\d*$"):
val = tf.strings.to_number(op[2], tf.int64)
else:
val = worry_level
if tf.equal(op[1], "+"):
ret = worry_level + val
if tf.equal(op[1], "*"):
ret = worry_level * val
return ret
@tf.function
def monkey_play(rounds):
items = tf.TensorArray(tf.int64, size=1, dynamic_size=True)
operation = tf.TensorArray(tf.string, size=1, dynamic_size=True)
divisible_test = tf.TensorArray(tf.int64, size=1, dynamic_size=True)
throw_if_true = tf.TensorArray(tf.int32, size=1, dynamic_size=True)
throw_if_false = tf.TensorArray(tf.int32, size=1, dynamic_size=True)
for monkey_ready in dataset:
if monkey_ready:
idx = tf.strings.to_number(monkey[0], tf.int32)
items = items.write(
idx,
tf.strings.to_number(tf.strings.split(monkey[1], ","), tf.int64),
)
operation = operation.write(idx, monkey[2])
divisible_test = divisible_test.write(
idx, tf.strings.to_number(monkey[3], tf.int64)
)
throw_if_true = throw_if_true.write(
idx, tf.strings.to_number(monkey[4], tf.int32)
)
throw_if_false = throw_if_false.write(
idx, tf.strings.to_number(monkey[5], tf.int32)
)
if tf.equal(part, 1):
divisor = tf.constant(3, tf.int64)
else:
divisor = tf.reduce_prod(divisible_test.stack())
for r in tf.range(rounds):
# Now items contains all the starting items for every monkey
# Let's play
for m in tf.range(monkey_count):
m_items = items.read(m)
op = operation.read(m)
test = divisible_test.read(m)
# tf.print("Monkey ", m, ":")
for i in tf.range(tf.shape(m_items)[0]):
# tf.print(
# " Monkey inspects an item with a worry level of ", m_items[i]
# )
worry_level = apply_operation(m_items[i], op)
# tf.print(
# " Worry level is processed accoring to: ",
# op,
# " becoming: ",
# worry_level,
# )
if tf.equal(part, 1):
worry_level //= divisor
# tf.print(
# " Monkey gets bored with item. Worry level is divided by 3 to ",
# worry_level,
# )
else:
worry_level = tf.math.mod(worry_level, divisor)
if tf.equal(tf.math.mod(worry_level, test), 0):
dest = throw_if_true.read(m)
else:
dest = throw_if_false.read(m)
# tf.print("dest items before: ", items.read(dest))
items = items.write(
dest,
tf.concat(
[items.read(dest), tf.expand_dims(worry_level, axis=0)],
axis=0,
),
)
# tf.print("dest items: ", items.read(dest))
update = tf.tensor_scatter_nd_add(
inspected_count,
[[tf.cast(m, tf.int64)]],
[tf.constant(1, tf.int64)],
)
inspected_count.assign(update)
items = items.write(m, [])
# tf.print("after: ", items.concat(), summarize=-1)
monkey_play(20)
top_values, _ = tf.math.top_k(inspected_count, k=2)
monkey_business = tf.reduce_prod(top_values)
tf.print("Part 1: ", monkey_business)
inspected_count.assign(tf.zeros_like(inspected_count))
part.assign(2)
monkey_play(10000)
top_values, _ = tf.math.top_k(inspected_count, k=2)
monkey_business = tf.reduce_prod(top_values)
tf.print("Part 2: ", monkey_business)
return 0
if __name__ == "__main__":
INPUT: Path = Path(sys.argv[1] if len(sys.argv) > 1 else "fake")
sys.exit(main(INPUT))