-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadv20.py
1575 lines (1291 loc) · 46.4 KB
/
adv20.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os, sys, re, math, subprocess
import operator, itertools, functools, collections
import timeit, random, time, builtins
assert sys.hexversion >= 0x03080000
# exec(open('adv20.py').read())
# ###########################################################################
# ###########################################################################
#
# 2020 DAY 25
#
# ###########################################################################
# 18433997
def d20251(input = None):
def find_loop_size(key, subject):
value = 1
for n in itertools.count(1):
value *= subject
value %= 20201227
if value == key: break
return n
def transform_loop(subject, loop_size):
value = 1
for n in itertools.count(1):
value *= subject
value %= 20201227
if n == loop_size: break
return value
# cards_key = 5764801
# doors_key = 17807724
# input = input or open('inputs/2025.in').read()
# cards_key, doors_key = map(int, input.splitlines())
cards_key = 18499292
doors_key = 8790390
cards_loop = find_loop_size(key=cards_key, subject=7) # 8
doors_loop = find_loop_size(key=doors_key, subject=7) # 11
print(cards_loop)
print(doors_loop)
print(transform_loop(doors_key, cards_loop))
print(transform_loop(cards_key, doors_loop))
# ###########################################################################
#
# 2020 DAY 24
#
# ###########################################################################
# http://3dmdesign.com/development/hexmap-coordinates-the-easy-way
#
# NW NE
# / \
# W | | E (X+1)
# \ /
# SW SE
# (Y+1) (X+1,Y+1)
#
def hexmove(s):
x, y, i = 0, 0, 0
while i < len(s):
if s[i:i+1] == 'e':
x += 1
i += 1
elif s[i:i+2] == 'se':
x += 1; y += 1
i += 2
elif s[i:i+2] == 'sw':
y += 1
i += 2
elif s[i:i+1] == 'w':
x -= 1
i += 1
elif s[i:i+2] == 'nw':
x -= 1; y -= 1
i += 2
elif s[i:i+2] == 'ne':
y -= 1
i += 2
else: assert 0
return (x, y)
# 293
def d20241(input = None):
input = input or open('inputs/2024.in').read().splitlines()
tiles = collections.defaultdict(int)
for line in input:
tiles[hexmove(line)] ^= 1
print(sum(tiles.values()))
# 3967
def d20242(input = None):
input = input or open('inputs/2024.in').read().splitlines()
def neighs(x, y):
return [
(x+1, y), (x-1, y), # E W
(x+1, y+1), (x-1, y-1), # SE NW
(x, y+1), (x, y-1)] # SW NE
def nbactive(x, y):
return sum(tiles[(nx, ny)] for (nx, ny) in neighs(x, y))
tiles = collections.defaultdict(int)
for line in input:
tiles[hexmove(line)] ^= 1
for n in itertools.count(1):
ntiles = collections.defaultdict(int)
xs, ys = list(zip(*tiles.keys()))
for (x, y) in (
(x, y)
for x in range(min(xs) - 1, max(xs) + 2)
for y in range(min(ys) - 1, max(ys) + 2)):
nb = nbactive(x, y)
if tiles[(x, y)]:
ntiles[x, y] = 0 if (nb == 0 or nb > 2) else 1
else:
ntiles[x, y] = 1 if (nb == 2) else 0
tiles = ntiles
print(n, sum(tiles.values()))
if n == 100: break
print(sum(tiles.values()))
# ###########################################################################
#
# 2020 DAY 23
#
# ###########################################################################
# 25468379
def d20231(input = None):
input = input or open('inputs/2023.in').read().strip() # 193467258
input = collections.deque(map(int, input), maxlen=len(input))
nbrounds = 100
max_value = max(input)
for n in itertools.count(1):
current = input.popleft()
input.appendleft(current)
# pick up the three cups
input.rotate(-1)
c1 = input.popleft()
c2 = input.popleft()
c3 = input.popleft()
input.rotate(+1)
# select a destination cup
destination = current
while True:
destination = destination - 1
if destination == 0: destination = max_value
if not destination in [c1, c2, c3]: break
destination_index = input.index(destination) # long
# insert cups
input.rotate(-destination_index-1)
input.extendleft([c3, c2, c1])
input.rotate(destination_index)
if n == nbrounds: break
input.rotate(-input.index(1))
result = ''.join((map(str, list(input)[1:])))
print(f'XXX {n=} {result=}')
# 474747880250
def d20232(input = None):
input = input or open('inputs/2023.in').read().strip() # 193467258
max_value = 1_000_000 # 9
input = list(map(int, input))
input += list(range(max(input) + 1, max_value + 1))
nbrounds = 10_000_000
indct = dict(
zip(input, itertools.islice(itertools.cycle(input), 1, None) ))
current = input[0]
for n in itertools.count(1):
# pick up the three cups
c1 = indct[current]
c2 = indct[c1]
c3 = indct[c2]
indct[current] = indct[c3]
# select a destination cup
destination = current
while True:
destination = destination - 1
if destination == 0: destination = max_value
if not destination in [c1, c2, c3]: break
# insert cups
prev_dest_next = indct[destination]
indct[destination] = c1
indct[c3] = prev_dest_next
# select new current
current = indct[current]
if n == nbrounds: break
print(indct[1] * indct[indct[1]])
# ###########################################################################
#
# 2020 DAY 22
#
# ###########################################################################
# 30138
def d20221():
input = open('inputs/2022.in').read()
p1, p2 = list(map(lambda x: list(map(
int, x.splitlines()[1:])), input.split('\n\n')))
while p1 and p2:
f1, f2 = p1.pop(0), p2.pop(0)
if f1 > f2:
p1.extend([f1, f2])
else:
p2.extend([f2, f1])
winner = p1 or p2
print(sum(map(lambda n_v: (n_v[0] + 1) * n_v[1], enumerate(reversed(winner)))))
# 31587
def d20222():
input = open('inputs/2022.in').read()
p1, p2 = list(map(lambda x: list(map(
int, x.splitlines()[1:])), input.split('\n\n')))
def recgame(p1, p2):
print(f'# new game {p1=} {p2=} ')
seen = set([])
while p1 and p2:
roundstr = f'{p1=} {p2=}'
print('# ### new round', roundstr)
if roundstr in seen:
print('# ### -->> already seen')
return True # XXX ?
seen.add(roundstr)
f1, f2 = p1.pop(0), p2.pop(0)
if len(p1) >= f1 and len(p2) >= f2:
w1 = recgame(p1[:f1], p2[:f2])
else:
w1 = f1 > f2
if w1:
p1.extend([f1, f2])
else:
p2.extend([f2, f1])
score = sum(map(lambda n_v: (n_v[0] + 1) * n_v[1], enumerate(reversed(p1 or p2))))
print(f'# --> end game {p1=} {p2=} --> {score=}')
return bool(p1)
recgame(p1, p2)
# ###########################################################################
#
# 2020 DAY 21
#
# ###########################################################################
# mxmxvkd kfcds sqjhc nhms (contains dairy, fish)
# trh fvjkl sbzzf mxmxvkd (contains dairy)
# sqjhc fvjkl (contains soy)
# sqjhc mxmxvkd sbzzf (contains fish)
# 2020
def d20211():
input = open('inputs/2021.in').read()
input = list(tuple(
map(str.split, re.sub('\W', ' ', line).split('contains'))
) for line in input.splitlines())
ingreds = list(set(sum(map(operator.itemgetter(0), input), [])))
allergs = list(set(sum(map(operator.itemgetter(1), input), [])))
print('ING', ingreds)
print('ALG', allergs)
poss = dict((alg, set(ingreds)) for alg in allergs)
for (ings, algs) in input:
for alg in algs: poss[alg] &= set(ings)
print('POS0', poss)
done = set({})
while True:
alg, ings = list(
filter(lambda k_v: (k_v[0] not in done) and (len(k_v[1]) == 1), poss.items()))[0]
for kalg in (poss.keys() - set([alg])): poss[kalg] -= ings
done.add(alg)
if done == set(allergs): break
print('POS1', poss)
not_allergs = set(ingreds) - set([]).union(*list(poss.values()))
print(sum(len(set(ings).intersection(not_allergs)) for (ings, algs) in input))
# bcdgf,xhrdsl,vndrb,dhbxtb,lbnmsr,scxxn,bvcrrfbr,xcgtv
def d20212():
input = open('inputs/2021.in').read()
input = list(tuple(
map(str.split, re.sub('\W', ' ', line).split('contains'))
) for line in input.splitlines())
ingreds = list(set(sum(map(operator.itemgetter(0), input), [])))
allergs = list(set(sum(map(operator.itemgetter(1), input), [])))
print('ING', ingreds)
print('ALG', allergs)
poss = dict((alg, set(ingreds)) for alg in allergs)
for (ings, algs) in input:
for alg in algs: poss[alg] &= set(ings)
print('POS0', poss)
done = set({})
while True:
alg, ings = list(
filter(lambda k_v: (k_v[0] not in done) and (len(k_v[1]) == 1), poss.items()))[0]
for kalg in (poss.keys() - set([alg])): poss[kalg] -= ings
done.add(alg)
if done == set(allergs): break
print('POS1', poss)
print(','.join(
(ings.pop()) for (alg, ings) in sorted(poss.items(), key=operator.itemgetter(0))))
# ###########################################################################
#
# 2020 DAY 20
#
# ###########################################################################
# #...##.#.. ..###..### #.#.#####.
# ..#.#..#.# ###...#.#. .#..######
# .###....#. ..#....#.. ..#.......
# ###.##.##. .#.#.#..## ######....
# .###.##### ##...#.### ####.#..#.
# .##.#....# ##.##.###. .#...#.##.
# #...###### ####.#...# #.#####.##
# .....#..## #...##..#. ..#.###...
# #.####...# ##..#..... ..#.......
# #.##...##. ..##.#..#. ..#.###...
# #.##...##. ..##.#..#. ..#.###...
# ##..#.##.. ..#..###.# ##.##....#
# ##.####... .#.####.#. ..#.###..#
# ####.#.#.. ...#.##### ###.#..###
# .#.####... ...##..##. .######.##
# .##..##.#. ....#...## #.#.#.#...
# ....#..#.# #.#.#.##.# #.###.###.
# ..#.#..... .#.##.#..# #.###.##..
# ####.#.... .#..#.##.. .######...
# ...#.#.#.# ###.##.#.. .##...####
# ...#.#.#.# ###.##.#.. .##...####
# ..#.#.###. ..##.##.## #..#.##..#
# ..####.### ##.#...##. .#.#..#.##
# #..#.#..#. ...#.#.#.. .####.###.
# .#..####.# #..#.#.#.# ####.###..
# .#####..## #####...#. .##....##.
# ##.##..#.. ..#...#... .####...#.
# #.#.###... .##..##... .####.##.#
# #...###... ..##...#.. ...#..####
# ..#.#....# ##.#.#.... ...##.....
# 17250897231301
def d20201():
input = open('inputs/2020.in').read()
grids = list(
paragr.splitlines() for paragr in input.split('\n\n'))
grids = dict(
(int(first[5:-1]), grid) for (first, *grid) in grids)
sides = {}
for (gridnum, lines) in grids.items():
sides.setdefault(gridnum, [])
sides[gridnum].append(lines[0])
sides[gridnum].append(lines[-1])
sides[gridnum].append(''.join(line[0] for line in lines))
sides[gridnum].append(''.join(line[-1] for line in lines))
sides[gridnum].extend(
''.join(reversed(side)) for side in list(sides[gridnum]))
poss = {}
for ((g1, s1), (g2, s2)) in itertools.combinations(sides.items(), 2):
if not len(set(s1) & set(s2)): continue
poss[g1] = poss.setdefault(g1, 0) + 1
poss[g2] = poss.setdefault(g2, 0) + 1
corners = sorted(poss.items(), key=operator.itemgetter(1))[:4]
print(list(map(operator.itemgetter(0), corners)))
print(functools.reduce(operator.mul, map(operator.itemgetter(0), corners)))
# 1576
def d20202():
input = open('inputs/2020.in').read()
grids = list(
paragr.splitlines() for paragr in input.split('\n\n'))
grids = dict(
(int(first[5:-1]), list(map(list, grid))) for (first, *grid) in grids)
def sides(grid):
yield from [
grid[0],
list(line[-1] for line in grid),
grid[-1],
list(line[0] for line in grid)]
def variants(grid):
yield grid
for i in range(3):
yield (grid := list(map(list, zip(*grid[::-1]))))
yield (grid := list(grid[::-1]))
for i in range(3):
yield (grid := list(map(list, zip(*grid[::-1]))))
big_grid, grid_pos = {}, {} # pos -> grid, grid -> pos
pending, todo = [], list(grids.keys())
pending.append(first := todo.pop())
big_grid[(0, 0)] = grids[first]
grid_pos[first] = (0, 0)
while pending:
grid = pending.pop()
for (sidenum, side) in enumerate(sides(big_grid[grid_pos[grid]])):
grid_x, grid_y = grid_pos[grid]
grid_nx = grid_x + {0:0, 1:1, 2:0, 3:-1}[sidenum]
grid_ny = grid_y + {0:-1, 1:0, 2:1, 3:0}[sidenum]
if big_grid.get((grid_nx, grid_ny), None): continue
for other in todo:
for variant in variants(grids[other]):
variant_sides = list(sides(variant))
if variant_sides[(sidenum + 2) % 4] == side:
big_grid[(grid_nx, grid_ny)] = variant
grid_pos[other] = (grid_nx, grid_ny)
pending.append(other)
todo.remove(other)
break
else: continue
break
image_lines = []
nb_lines = len(big_grid[(0,0)]) - 2
xs, ys = list(zip(*big_grid.keys()))
for y in range(min(ys), max(ys) + 1):
for x in range(min(xs), max(xs) + 1):
for (n, line) in enumerate(big_grid[(x, y)][1:-1]):
if x == min(xs): image_lines.append('')
line = ''.join(line[1:-1])
image_lines[(y - min(ys)) * nb_lines + n] += line
pass
print('\n'.join(image_lines))
# ....................
# . #
# .# ## ## ###
# . # # # # # #
monster = [
(0, 18),
(1, 0), (1, 5), (1, 6), (1, 11), (1, 12), (1, 17), (1, 18), (1, 19),
(2, 1), (2, 4), (2, 7), (2, 10), (2, 13), (2, 16)]
for variant in variants(image_lines):
found = False
for y in range(len(variant) - 1):
for x in range(len(variant[0]) - 18):
for (dy, dx) in monster:
if not variant[y + dy][x + dx] in ['#', 'O']: break
else:
print(x, y)
for (dy, dx) in monster: variant[y + dy][x + dx] = 'O'
found = True
if not found: continue
print('\n'.join(map(lambda l: ''.join(l), variant)) + '\n')
break
print(len(list(filter(lambda c: c == '#', sum(variant, [])))))
# .####...#####..#...###..
# #####..#..#.#.####..#.#.
# .#.#...#.###...#.##.O#..
# #.O.##.OO#.#.OO.##.OOO##
# ..#O.#O#.O##O..O.#O##.##
# ...#.#..##.##...#..#..##
# #.##.#..#.#..#..##.#.#..
# .###.##.....#...###.#...
# #.####.#.#....##.#..#.#.
# ##...#..#....#..#...####
# ..#.##...###..#.#####..#
# ....#.##.#.#####....#...
# ..##.##.###.....#.##..#.
# #...#...###..####....##.
# .#.##...#.##.#.#.###...#
# #.###.#..####...##..#...
# #.###...#.##...#.##O###.
# .O##.#OO.###OO##..OOO##.
# ..O#.O..O..O.#O##O##.###
# #.#..##.########..#..##.
# #.#####..#.#...##..#....
# #....##..#.#########..##
# #...#.....#..##...###.##
# #..###....##.#...##.##.#
# ###########################################################################
#
# 2020 DAY 19
#
# ###########################################################################
def match2019(rules, str):
def check(rulenum, endstr):
rule = rules.get(rulenum)
# simple poss with character
if rule[0][0].startswith('"'):
if not endstr.startswith(rule[0][0][1]):
return set([])
return set([endstr[1:]])
# sequence of other rules
all_matches = set()
for poss in rule:
poss_matches = set([endstr])
for elem in poss:
match_elem = set()
for end in poss_matches:
match_elem |= check(int(elem), end)
poss_matches = match_elem
all_matches |= poss_matches
return all_matches
return '' in check(0, str)
# 109
def d20191():
input = open('inputs/2019.in').read()
rules, input = map(str.splitlines, input.split('\n\n'))
rules = dict(itertools.starmap(lambda n, v: (int(n), list(
e.strip().split() for e in v.split('|'))), map(lambda l: l.split(':'), rules)))
print(len(list(filter(lambda i: match2019(rules, i), input))))
# 301
def d20192():
input = open('inputs/2019.in').read()
rules, input = map(str.splitlines, input.split('\n\n'))
rules = dict(itertools.starmap(lambda n, v: (int(n), list(
e.strip().split() for e in v.split('|'))), map(lambda l: l.split(':'), rules)))
rules.update({8: [['42'], ['42', '8']], 11: [['42', '31'], ['42', '11', '31']]})
print(len(list(filter(lambda i: match2019(rules, i), input))))
# ###########################################################################
#
# 2020 DAY 18
#
# ###########################################################################
# 14006719520523
def d20181(input = None):
input = input or open('inputs/2018.in').read()
input = input.splitlines()
def evalx(expr):
class advint(int):
def __add__(self, b):
return advint(int(self) + b)
def __sub__(self, b):
return advint(int(self) * b)
expr = ''.join(map(lambda c: {'*':'-'}.get(c, c), expr))
expr = re.sub('(\d+)', 'advint(\\1)', expr)
return eval(expr)
print(sum(evalx(line) for line in input))
# 545115449981968
def d20182(input = None):
input = input or open('inputs/2018.in').read()
input = input.splitlines()
def evalx(expr):
class advint(int):
def __add__(self, b):
return advint(int(self) * b)
def __mul__(self, b):
return advint(int(self) + b)
expr = ''.join(map(lambda c: {'+':'*', '*':'+'}.get(c, c), expr))
expr = re.sub('(\d+)', 'advint(\\1)', expr)
return eval(expr)
print(sum(evalx(line) for line in input))
# def d20181_re(input = None):
# input = input or open('inputs/2018.in').read()
# input = input.splitlines()
#
# def evalx(expr):
# while True:
# while (re_obj := re.search('(^|\()((\d+) (\+|\*) (\d+))', expr)):
# expr = re.sub(re_obj.re, re_obj.group(1) + str(eval(re_obj.group(2))), expr, count=1)
# while (re_obj := re.search('\((\d+)\)', expr)):
# expr = re.sub(re_obj.re, '\\1', expr, count=1)
# if (re.match('^\d+$', expr)): break
# return int(expr)
#
# print(sum(evalx(line) for line in input))
# def d20181_pr(input = None):
# input = input or open('inputs/2018.in').read()
# input = input.splitlines()
#
# class parser_():
# def __init__(self, str):
# self.lexer = (t.group(0) for t in re.finditer('(\(|\+|\*|\d+|\))', str))
# self.token = next(self.lexer)
#
# def check_token(self, x):
# if isinstance(x, str):
# return self.token == x
# else: # func for token type check
# return x(self.token)
#
# def advance(self):
# self.prev_token = self.token
# try: self.token = next(self.lexer)
# except StopIteration: pass
#
# def accept(self, c):
# if not self.check_token(c): return False
# self.advance()
# return True
#
# def expect(self, c):
# assert self.check_token(c)
# self.advance()
# return True
#
# # expr -> term
# # term -> fact "+" fact | fact
# # fact -> prim "*" prim | prim
# # prim -> NUMBER | "(" expr ")"
#
# def evalx(s):
#
# def parse_expr(parser):
# expr1 = parse_fact(parser)
# if parser.accept('+'):
# expr2 = parse_fact(parser)
# return expr1 + expr2
# return expr1
#
# def parse_fact(parser):
# expr1 = parse_prim(parser)
# if parser.accept('*'):
# expr2 = parse_prim(parser)
# return expr1 * expr2
# return expr1
#
# def parse_prim(parser):
# if parser.accept('('):
# expr = parse_expr(parser)
# parser.expect(')')
# return expr
# elif parser.accept(str.isnumeric):
# expr = int(parser.prev_token)
# return expr
# else: assert 0
#
# return parse_expr(parser_(s))
#
# print(evalx(input[0]))
# ###########################################################################
#
# 2020 DAY 17
#
# ###########################################################################
input17 = """#.##.##.
.##..#..
....#..#
.##....#
#..##...
.###..#.
..#.#..#
.....#..
"""
input170 = """.#.\n..#\n###\n"""
# 273
def d20171(input = None):
input = input or open('inputs/2017.in').read()
grid = collections.defaultdict(int, (
((x, y, 0), 1)
for (y, l) in enumerate(input.splitlines())
for (x, c) in enumerate(l.strip()) if c == '#'))
def neighs(x, y, z):
return (
(nx, ny, nz)
for nx in range(x - 1, x + 2)
for ny in range(y - 1, y + 2)
for nz in range(z - 1, z + 2)
if (nx, ny, nz) != (x, y, z))
def nbactive(x, y, z):
return sum(grid[(nx, ny, nz)] for (nx, ny, nz) in neighs(x, y, z))
for n in range(6):
ngrid = collections.defaultdict(int)
xs, ys, zs = list(zip(*grid.keys()))
for (x, y, z) in (
(x, y, z)
for x in range(min(xs) - 1, max(xs) + 2)
for y in range(min(ys) - 1, max(ys) + 2)
for z in range(min(zs) - 1, max(zs) + 2)):
if grid[(x, y, z)]:
ngrid[(x, y, z)] = (2 <= nbactive(x, y, z) <= 3) and 1 or 0
else:
ngrid[(x, y, z)] = (nbactive(x, y, z) == 3) and 1 or 0
grid = ngrid
print(sum(grid.values()))
# 1504
def d20172(input = None):
input = input or open('inputs/2017.in').read()
grid = collections.defaultdict(int, (
((x, y, 0, 0), 1)
for (y, l) in enumerate(input.splitlines())
for (x, c) in enumerate(l.strip()) if c == '#'))
def neighs(x, y, z, w):
return (
(nx, ny, nz, nw)
for nx in range(x - 1, x + 2)
for ny in range(y - 1, y + 2)
for nz in range(z - 1, z + 2)
for nw in range(w - 1, w + 2)
if (nx, ny, nz, nw) != (x, y, z, w))
def nbactive(x, y, z, w):
return sum(grid[(nx, ny, nz, nw)] for (nx, ny, nz, nw) in neighs(x, y, z, w))
for n in range(6):
ngrid = collections.defaultdict(int)
xs, ys, zs, ws = list(zip(*grid.keys()))
for (x, y, z, w) in (
(x, y, z, w)
for x in range(min(xs) - 1, max(xs) + 2)
for y in range(min(ys) - 1, max(ys) + 2)
for z in range(min(zs) - 1, max(zs) + 2)
for w in range(min(ws) - 1, max(ws) + 2)):
if grid[(x, y, z, w)]:
ngrid[(x, y, z, w)] = (2 <= nbactive(x, y, z, w) <= 3) and 1 or 0
else:
ngrid[(x, y, z, w)] = (nbactive(x, y, z, w) == 3) and 1 or 0
grid = ngrid
print(sum(grid.values()))
# ###########################################################################
#
# 2020 DAY 16
#
# ###########################################################################
# 18142
def d20161():
input = open('inputs/2016.in').read()
par1, par2, par3 = input.split('\n\n')
ranges = list(
map(lambda t: list(map(int, t)), re.findall(
'^.+: (\d+)-(\d+) or (\d+)-(\d+)', par1, re.MULTILINE)))
mytckt = list(
map(int, par2.splitlines()[1].split(',')))
nearbt = list(
map(lambda l: list(map(int, l.split(','))), par3.splitlines()[1:]))
valids = set(sum(
(list(range(a1, a2 + 1)) + list(range(b1, b2 + 1))
for (a1, a2, b1, b2) in ranges), []))
tserate = sum(sum(
list(filter(bool, map(lambda l: list(set(l) - valids), nearbt))), []))
print(tserate)
# 1069784384303
def d20162():
input = open('inputs/2016.in').read()
par1, par2, par3 = input.split('\n\n')
ranges = list(
map(lambda t: (t[0], list(map(int, t[1:]))), re.findall(
'(^.+): (\d+)-(\d+) or (\d+)-(\d+)', par1, re.MULTILINE)))
mytckt = list(
map(int, par2.splitlines()[1].split(',')))
nearbt = list(
map(lambda l: list(map(int, l.split(','))), par3.splitlines()[1:]))
valids = set(sum(
(list(range(a1, a2 + 1)) + list(range(b1, b2 + 1))
for (_, (a1, a2, b1, b2)) in ranges), []))
nearbt = list(
filter(lambda l: not len(set(l) - valids), nearbt))
posspos = dict(
(rid, set(range(max(map(len, nearbt)))).intersection(
*((set(n for (n, v) in enumerate(nt)
if a1 <= v <= a2 or b1 <= v <= b2)) for nt in nearbt)))
for (rid, (a1, a2, b1, b2)) in ranges)
todo, done = posspos, {}
while todo:
todo = dict(sorted(todo.items(), key=lambda k_v: len(k_v[1])))
(firstid, values) = list(todo.items())[0]
assert len(values) == 1
value = list(values)[0]
done[firstid] = value
del todo[firstid]
todo = dict((k, set(filter(lambda x: x != value, v))) for (k, v) in todo.items())
indexes = list(
map(lambda k_v: k_v[1], filter(
lambda k_v: k_v[0].startswith('departure'), done.items())))
print(functools.reduce(operator.mul, (mytckt[i] for i in indexes), 1))
# ###########################################################################
#
# 2020 DAY 15
#
# ###########################################################################
# 2020 # [2, 1, 10, 11, 0, 6]
# 2020 # [0, 3, 6] # 436
# 2020 # [1, 3, 2] # 1
# 2020 # [2, 1, 3] # 10
# 2020 # [1, 2, 3] # 27
# 2020 # [2, 3, 1] # 78
# 2020 # [3, 2, 1] # 438
# 2020 # [3, 1, 2] # 1836
# 232
def d20151():
input = list(map(int, open('inputs/2015.in').read().split(',')))
# input = [2, 1, 10, 11, 0, 6]
limit = 2020
last_spoken = '?'
idx = collections.defaultdict(int)
for n in itertools.count(1):
spoken = (
(input.pop(0)) if input else
(n - idx[last_spoken] - 1) if idx[last_spoken] else 0)
idx[last_spoken] = n - 1
last_spoken = spoken
if n == limit: break
print(spoken)
#18929178
def d20152():
input = list(map(int, open('inputs/2015.in').read().split(',')))
limit = 30000000
last_spoken = '?'
idx = collections.defaultdict(int)
for n in itertools.count(1):
spoken = (
(input.pop(0)) if input else
(n - idx[last_spoken] - 1) if idx[last_spoken] else 0)
idx[last_spoken] = n - 1
last_spoken = spoken
if n == limit: break
print(spoken)
# ###########################################################################
#
# 2020 DAY 14
#
# ###########################################################################
# 4886706177792
def d20141():
input = open('inputs/2014.in').read().splitlines()
memory = collections.defaultdict(int)
for stmt in input:
if stmt.startswith('mask'):
bmask = stmt.split()[-1]
elif stmt.startswith('mem'):
re_obj = re.match('^mem\[(\d+)\] = (\d+)$', stmt)
idx, val = list(map(int, re_obj.groups()))
val = val | int(bmask.replace('X', '0'), 2)
val = val & int(bmask.replace('X', '1'), 2)
memory[idx] = val
else: assert 0
print(sum(memory.values()))
# 3348493585827
def d20142():
input = open('inputs/2014.in').read().splitlines()
memory = collections.defaultdict(int)
for stmt in input:
if stmt.startswith('mask'):
bmask = stmt.split()[-1]
elif stmt.startswith('mem'):
re_obj = re.match('^mem\[(\d+)\] = (\d+)$', stmt)
idx, val = list(map(int, re_obj.groups()))
# XXXXXXXXXXXXXXX
xis = list(map(lambda n_x: n_x[0], filter(
lambda n_x: n_x[1] == 'X', enumerate(bmask.replace('1', '0')))))
for xvs in itertools.product(['0','1'], repeat=len(xis)):
nidx = idx | int(bmask.replace('X', '0'), 2)
nidx = list(format(nidx, '036b'))
for (xi, xv) in zip(xis, xvs):
nidx[xi] = xv
nidx = int(''.join(nidx), 2)
memory[nidx] = val
# XXXXXXXXXXXXXXX
else: assert 0
print(sum(memory.values()))
# ###########################################################################
#
# 2020 DAY 13
#
# ###########################################################################
# 4207
def d20131():
input = open('inputs/2013.in').read().splitlines()
tms, ids = int(input[0]), list(map(int, filter(
lambda x: x[0].isdigit(), input[1].split(','))))
wait, busid = min(map(lambda x: (x * (1 + tms // x) - tms, x), ids))
print(wait, busid, wait * busid)
# 725850285300475
def d20132():
input = open('inputs/2013.in').read().splitlines()
input = enumerate(int(x) if (x != 'x') else 0 for x in input[1].split(','))
input = list(filter(lambda n_i: bool(n_i[1]), input))
cur_time, cur_incr = 0, 1
for (bus_offset, bus_id) in input:
while (cur_time + bus_offset) % bus_id: