-
Notifications
You must be signed in to change notification settings - Fork 0
/
adv18.hs
2125 lines (1781 loc) · 79.3 KB
/
adv18.hs
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 runhaskell
import Data.Bits
import Data.Char
import Data.List
import Data.Array
import Data.Maybe
import Data.Tuple
import Debug.Trace
import Text.Printf
import Numeric
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Sequence as Seq
import qualified Data.ByteString.Lazy as BS
import Data.Digest.Pure.MD5
import System.Environment (getArgs)
import Test.HUnit
import Data.Foldable
-------------------------------------------------------------------
-------------------------------------------------------------------
main =
getArgs >>= getInput >>= return . solve1820_1 >>= print
where
getInput (l:_) = readFile l
getInput [] = getContents
-- readFile "inputs/180x.in" >>= return . solve18x_1
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
--
-- 2018 DAY 25
--
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
allConsts consts stars
| null stars = consts
| otherwise = allConsts (newof : dfconsts) (tail stars)
where
(ofconsts, dfconsts) = partition (belongsto (head stars)) consts
newof = ((head stars) : concat ofconsts)
belongsto s = any ((<= 3) . mandist4 s)
-- answer part one: 352
solve1825_1 =
length .
-- list of all constellations
allConsts [] .
-- list of all stars
map ((\(x1 : x2 : x3 : x4 : []) -> (x1, x2, x3, x4)) .
map toInt . splitOn (== ',')) . lines
-- -------------------------------------------------------------------
mandist4 (x1, y1, z1, t1) (x2, y2, z2, t2) =
(abs (x2 - x1)) + (abs (y2 - y1)) + (abs (z2 - z1)) + (abs (t2 - t1))
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
--
-- 2018 DAY 24
--
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
-- TODO cleanup
-- Immune System:
groups0 =
M.fromList [
-- units init hps attack dmg & type immunities & weaknesses
(("ims", 1), ( 889, 12, 3275, 36, "bludgeoning", ["cold"], ["bludgeoning", "radiation"])),
(("ims", 2), ( 94, 7, 1336, 127, "bludgeoning", [], ["radiation", "cold"])),
(("ims", 3), (1990, 20, 5438, 25, "slashing", [], [])),
(("ims", 4), (1211, 19, 6640, 54, "fire", [], [])),
(("ims", 5), (3026, 16, 7938, 26, "bludgeoning", ["cold"], ["bludgeoning"])),
(("ims", 6), (6440, 4, 9654, 14, "fire", [], [])),
(("ims", 7), (2609, 3, 8218, 28, "cold", [], ["bludgeoning"])),
(("ims", 8), (3232, 14, 11865, 30, "slashing", [], ["radiation"])),
(("ims", 9), (2835, 2, 7220, 18, "bludgeoning", ["fire", "radiation"], [])),
(("ims",10), (2570, 17, 4797, 15, "radiation", [], ["cold"])),
(("inf", 1), ( 333, 13, 44943, 223, "slashing", [], ["bludgeoning"])),
(("inf", 2), (1038, 8, 10867, 16, "cold", ["bludgeoning", "slashing", "fire"], [])),
(("inf", 3), ( 57, 5, 50892, 1732, "cold", [], [])),
(("inf", 4), ( 196, 6, 36139, 334, "fire", [], ["cold"])),
(("inf", 5), (2886, 1, 45736, 25, "cold", ["cold"], ["slashing"])),
(("inf", 6), (4484, 18, 37913, 16, "fire", ["fire", "radiation", "slashing"], ["bludgeoning"])),
(("inf", 7), (1852, 9, 49409, 52, "radiation", ["bludgeoning"], ["radiation"])),
(("inf", 8), (3049, 10, 18862, 12, "fire", [], ["radiation"])),
(("inf", 9), (1186, 15, 23898, 34, "bludgeoning", ["fire"], [])),
(("inf",10), (6003, 11, 12593, 2, "cold", [], []))
]
-- 889 units each with 3275 hit points (weak to bludgeoning, radiation; immune to cold) with an attack that does 36 bludgeoning damage at initiative 12
-- 94 units each with 1336 hit points (weak to radiation, cold) with an attack that does 127 bludgeoning damage at initiative 7
-- 1990 units each with 5438 hit points with an attack that does 25 slashing damage at initiative 20
-- 1211 units each with 6640 hit points with an attack that does 54 fire damage at initiative 19
-- 3026 units each with 7938 hit points (weak to bludgeoning; immune to cold) with an attack that does 26 bludgeoning damage at initiative 16
-- 6440 units each with 9654 hit points with an attack that does 14 fire damage at initiative 4
-- 2609 units each with 8218 hit points (weak to bludgeoning) with an attack that does 28 cold damage at initiative 3
-- 3232 units each with 11865 hit points (weak to radiation) with an attack that does 30 slashing damage at initiative 14
-- 2835 units each with 7220 hit points (immune to fire, radiation) with an attack that does 18 bludgeoning damage at initiative 2
-- 2570 units each with 4797 hit points (weak to cold) with an attack that does 15 radiation damage at initiative 17
-- Infection:
-- 333 units each with 44943 hit points (weak to bludgeoning) with an attack that does 223 slashing damage at initiative 13
-- 1038 units each with 10867 hit points (immune to bludgeoning, slashing, fire) with an attack that does 16 cold damage at initiative 8
-- 57 units each with 50892 hit points with an attack that does 1732 cold damage at initiative 5
-- 196 units each with 36139 hit points (weak to cold) with an attack that does 334 fire damage at initiative 6
-- 2886 units each with 45736 hit points (immune to cold; weak to slashing) with an attack that does 25 cold damage at initiative 1
-- 4484 units each with 37913 hit points (weak to bludgeoning; immune to fire, radiation, slashing) with an attack that does 16 fire damage at initiative 18
-- 1852 units each with 49409 hit points (immune to bludgeoning; weak to radiation) with an attack that does 52 radiation damage at initiative 9
-- 3049 units each with 18862 hit points (weak to radiation) with an attack that does 12 fire damage at initiative 10
-- 1186 units each with 23898 hit points (immune to fire) with an attack that does 34 bludgeoning damage at initiative 15
-- 6003 units each with 12593 hit points with an attack that does 2 cold damage at initiative 11
-- -------------------------------------------------------------------
-- Immune System:
-- 17 units each with 5390 hit points (weak to radiation, bludgeoning) with
-- an attack that does 4507 fire damage at initiative 2
-- 989 units each with 1274 hit points (immune to fire; weak to bludgeoning,
-- slashing) with an attack that does 25 slashing damage at initiative 3
--
-- Infection:
-- 801 units each with 4706 hit points (weak to radiation) with an attack
-- that does 116 bludgeoning damage at initiative 1
-- 4485 units each with 2961 hit points (immune to radiation; weak to fire,
-- cold) with an attack that does 12 slashing damage at initiative 4
groups1 =
M.fromList [
-- units init hps attack dmg & type immunities & weaknesses
(("ims", 1), ( 17, 2, 5390, 4507, "fire", [], ["radiation", "bludgeoning"])),
(("ims", 2), ( 989, 3, 1274, 25, "slashing", ["fire"], ["bludgeoning", "slashing"])),
(("inf", 1), ( 801, 1, 4706, 116, "bludgeoning", [], ["radiation"])),
(("inf", 2), (4485, 4, 2961, 12, "slashing", ["radiation"], ["fire", "cold"]))
]
-- -------------------------------------------------------------------
showGroups groups =
concat . map ((:) '\n') . map sgr . sort . M.assocs $ groups
where
sgr ((g, n), (u, i, h, a, _, _, _)) =
printf "%3s-gr%-2d | %4d units | %4d hp, %4d at, %d in" g n u h a i
selectTargets groups selection
-- | trace (show ("SELECT-1", choosers)) False = undefined
| null choosers = selection
-- | trace (show ("SELECT-2", fchooser, ennemies)) False = undefined
| null ennemies =
selectTargets groups (M.insert fchooser Nothing selection)
-- | trace (show ("SELECT-3", ftrgvals)) False = undefined
-- | trace (show ("SELECT-4", fselectd)) False = undefined
| dmg == 0 = -- trace (printf " SEL %3s-gr%d -> Nothing" fa fn) $
selectTargets groups (M.insert fchooser Nothing selection)
| otherwise = -- trace (printf " SEL %3s-gr%d -> %3s-gr%d" fa fn ea en) $
selectTargets groups (M.insert fchooser (Just (ea, en)) selection)
where
selorder (n, i, _, a, _, _, _) = (n * a, i)
choosers =
reverse . sortOn (selorder . (M.!) groups) $
((M.keys groups) \\ (M.keys selection))
fchooser @ (fa, fn) = head choosers
ennemies = filter (\(a, n) -> a /= fa) $
(M.keys groups) \\ (catMaybes $ M.elems selection)
trgorder ennemy
| elem ft ei = (0, (0, 0))
| elem ft ew = (2 * fn * fa, (en * ea, ev))
| otherwise = (fn * fa, (en * ea, ev))
where
(fn, _, _, fa, ft, _, _) = (M.!) groups fchooser
(en, ev, _, ea, _, ei, ew) = (M.!) groups ennemy
ftrgvals = reverse . sort . map (\e -> (trgorder e, e)) $ ennemies
fselectd @ ((dmg, (efp, ein)), (ea, en)) = head ftrgvals
attackTargets groups selection attackers
| null attackers = groups
-- | trace (show ("ATTACK-1", attackers)) False = undefined
-- | trace (show ("ATTACK-2", fattacker, fdefender)) False = undefined
| not $ M.member fattacker groups =
attackTargets groups selection (tail attackers)
| isNothing fdefender =
attackTargets groups selection (tail attackers)
-- | trace (show ("ATTACK-3", fdeadunts)) False = undefined
| (en - fdeadunts) <= 0 =
attackTargets newgroups1 selection (tail attackers)
| otherwise = attackTargets newgroups2 selection (tail attackers)
where
fattacker = head attackers
fdefender = (M.!) selection fattacker
fdeadunts
| elem ft ei = min en (0)
| elem ft ew = min en ((div) (2 * fn * fa) (eh))
| otherwise = min en ((div) (fn * fa) (eh))
(fn, _, _, fa, ft, _, _) = (M.!) groups fattacker
(en, ev, eh, ea, et, ei, ew) = (M.!) groups (fromJust fdefender)
newgroups1 =
M.delete (fromJust fdefender) groups
newgroups2 =
M.insert (fromJust fdefender) (en - fdeadunts, ev, eh, ea, et, ei, ew) groups
groupFight groups
-- | trace (showGroups groups) False = undefined
| (length armies <= 1) =
sum . map (\(n, _, _, _, _, _, _) -> n) . M.elems $ groups
-- | trace (show ("SELECT", selection)) False = undefined
-- | trace (show ("ATTACK", newgroups)) False = undefined
| otherwise = groupFight newgroups
where
armies = nub . map fst . M.keys $ groups
selection = selectTargets groups M.empty
atkorder (_, i, _, _, _, _, _) = i
attackers =
reverse . sortOn (atkorder . (M.!) groups) $
(M.keys groups)
newgroups = attackTargets groups selection attackers
-- answer part one: 18532
-- solve1824_1 _ = groupFight groups0
groupFight2 groups
-- | trace (showGroups groups) False = undefined
| (notElem "ims" armies) = 0
| (length armies <= 1) =
sum . map (\(n, _, _, _, _, _, _) -> n) . M.elems $ groups
-- | trace (show ("SELECT", selection)) False = undefined
-- | trace (show ("ATTACK", newgroups)) False = undefined
| otherwise = groupFight2 newgroups
where
armies = nub . map fst . M.keys $ groups
selection = selectTargets groups M.empty
atkorder (_, i, _, _, _, _, _) = i
attackers =
reverse . sortOn (atkorder . (M.!) groups) $
(M.keys groups)
newgroups = attackTargets groups selection attackers
testBoost groups boost
| trace (printf "BOOST %d" boost) False = undefined
| result == 0 = testBoost groups (boost + 1)
| otherwise = result
where
appBoost (g, _) (n, v, h, a, t, i, w)
| g == "ims" = (n, v, h, a + boost, t, i, w)
| otherwise = (n, v, h, a, t, i, w)
modgroups = M.mapWithKey appBoost groups
result = groupFight2 modgroups
-- answer part two: 6523 (boost = 29)
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
--
-- 2018 DAY 23
--
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
-- answer part one: 219
solve1823_1 input =
(strongest, inrange, length inrange)
where
bots = map (
(\(x : y : z : r : []) -> ((x, y, z), r)) .
map toInt . splitOn (flip elem "<=,rpos >")) . lines $ input
strongest @ ((xs, ys, zs), rs) = maximumOn (snd) bots
inrange = filter ((<= rs) . mandist3 (xs, ys, zs) . fst) $ bots
-- -------------------------------------------------------------------
-- reddit.com/r/adventofcode/comments/a99n7x/2018_day_23_part_2_explanation_with_visualization/
-- reddit.com/r/adventofcode/comments/a8s17l/2018_day_23_solutions/ecfmpy0
boxNIntersects bots sz (bx, by, bz) =
((bx, by, bz, sz),
length . filter (\((x, y, z), r) -> ((rd x bx (bx + sz - 1)) + (rd y by (by + sz - 1)) + (rd z bz (bz + sz - 1))) <= r) $ bots)
where rd v l h = if (v < l) then (l - v) else if (v > h) then (v - h) else 0
bestPoint bots open
| trace (show ((bx, by, bz, sz), nb)) False = undefined
| sz == 1 = (mandist3 (0, 0, 0) (bx, by, bz))
| otherwise = bestPoint bots (nxtboxes ++ (open \\ [((bx, by, bz, sz), nb)]))
where
((bx, by, bz, sz), nb) = maximumOn (\((x, y, z, s), n) -> (n, -(mandist3 (x, y, z) (0, 0, 0)))) open
hs = (div) sz 2
subboxes =
(bx, by, bz) : (bx + hs, by, bz) : (bx, by + hs, bz) : (bx + hs, by + hs, bz) :
(bx, by, bz + hs) : (bx + hs, by, bz + hs) : (bx, by + hs, bz + hs) : (bx + hs, by + hs, bz + hs) : []
nxtboxes = map (boxNIntersects bots hs) subboxes
-- answer part two: 83779034
solve1823_2 input =
bestPoint bots [boxNIntersects bots (2*po2v) (-po2v, -po2v, -po2v)]
where
bots = map (
(\(x : y : z : r : []) -> ((x, y, z), r)) .
map toInt . splitOn (flip elem "<=,rpos >")) . lines $ input
vmax = maximum . map abs . concat . map (\((x, y, z), _) -> [x, y, z]) $ bots
po2v = head . dropWhile (<= vmax) $ [2 ^ x | x <- [1..]]
-- -------------------------------------------------------------------
mandist3 (x1, y1, z1) (x2, y2, z2) =
(abs (x2 - x1)) + (abs (y2 - y1)) + (abs (z2 - z1))
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
--
-- 2018 DAY 22
--
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
showCave lmap (tx, ty) =
(concat . map color) . concat . map ((:) '\n') $
[[regty (x, y) | x <- [0 .. tx]] | y <- [0 .. ty]]
where
regty (x, y)
| (x, y) == (tx, ty) = 'T'
| (x, y) == (0, 0) = 'M'
| otherwise = regType $ getErLevel lmap (x, y)
color x
| x == '|' = printf "\ESC[1;32m\ \%c\ \\ESC[0;m" x
| x == '=' = printf "\ESC[1;34m\ \%c\ \\ESC[0;m" x
| x == '.' = printf "\ESC[1;31m\ \%c\ \\ESC[0;m" x
| otherwise = printf "%c" x
getErLevel lmap (x, y)
| M.member (x, y) lmap = (M.!) lmap (x, y)
| otherwise = undefined
mapELevel depth (tx, ty) =
foldl (setErLevel (tx, ty) depth) M.empty $
-- XXXX [(x, y) | y <- [0 .. ty], x <- [0 .. tx]]
[(x, y) | y <- [0 .. 1000], x <- [0 .. 100]]
geoIndex target lmap (x, y)
| (x, y) == (0, 0) = 0
| (x, y) == target = 0
| (y == 0) = x * 16807
| (x == 0) = y * 48271
| otherwise =
(getErLevel lmap (x - 1, y)) * (getErLevel lmap (x, y - 1))
regType el
| m == 0 = '.'
| m == 1 = '='
| m == 2 = '|'
where m = ((mod) el 3)
setErLevel target depth lmap (x, y) =
M.insert (x, y) l lmap
where l = (mod (geoIndex target lmap (x, y) + depth) 20183)
-- depth: 510
-- target: 10,10
-- depth: 11991
-- target: 6,797
-- answer part one: 5622
solve1822_1 depth tx ty
| trace (showCave lmap (tx, ty)) False = undefined
| otherwise = sum $ map (flip (mod) 3) . M.elems $ lmap
where lmap = mapELevel depth (tx, ty)
-- -------------------------------------------------------------------
-- neither: '0'
-- torch: 'T'
-- climbing gear: 'C'
-- astar with mandist as heuristic
shortestPath lmap (tx, ty) closed open
| trace (printf "%3d %3d %c | %3d | %3d" x y t d (d + mandist (x, y) (tx, ty))) False = undefined
| (x, y, t) == (tx, ty, 'T') = d
| otherwise = shortestPath lmap (tx, ty) (S.insert (x, y, t) closed) next_open
where
((x, y, t), d) = minimumOn (\((x, y, t), d) -> d + mandist (x, y) (tx, ty)) open
rt = regType $ getErLevel lmap (x, y)
other_tool
| rt == '.' = head $ ['C', 'T'] \\ [t]
| rt == '=' = head $ ['C', '0'] \\ [t]
| rt == '|' = head $ ['T', '0'] \\ [t]
isValid rt
| rt == '.' = t /= '0'
| rt == '=' = t /= 'T'
| rt == '|' = t /= 'C'
next_cells =
filter (isValid . regType . getErLevel lmap) .
filter (flip M.member lmap) $
[(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
next_moves = ((x, y, other_tool), d + 7) : [((nx, ny, t), d + 1) | (nx, ny) <- next_cells]
unqmin_nxt = M.assocs . M.fromListWith min $ (next_moves ++ open)
next_open = filter (\((x, y, t), d) -> S.notMember (x, y, t) closed) unqmin_nxt
-- TODO: too long
-- answer part two: 1089
solve1822_2 depth tx ty
| trace (showCave lmap (tx, ty)) False = undefined
| otherwise =
shortestPath lmap (tx, ty) S.empty [((0, 0, 'T'), 0)]
where lmap = mapELevel depth (tx, ty)
-- (1363.24 secs, 865,040,929,440 bytes)
minimumOn f = minimumBy (\x1 x2 -> compare (f x1) (f x2))
maximumOn f = maximumBy (\x1 x2 -> compare (f x1) (f x2))
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
--
-- 2018 DAY 21
--
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
execProgX regs ipr imap
| M.notMember pc imap = [((M.!) regs 0)]
-- | pc == 28,
-- trace ((printf "%2d | %s %3d %3d %3d | " pc opc ra rb rc) ++
-- (concat . map (printf "%16d") . M.elems $ regs)) False = undefined
| pc == 28 = ((M.!) regs 3) : execProgX nregs ipr imap
| otherwise = execProgX nregs ipr imap
where
pc = (M.!) regs ipr
(opc, ra, rb, rc) = (M.!) imap pc
iregs = execInstr regs opc ra rb rc
nregs = M.adjust (+1) ipr iregs
-- answer part one: 3909249
solve1821_1 input =
head $ execProgX regs0 ipr imap
where
(ipline : inlines) = lines $ input
ipr = toInt . last . words $ ipline
imap = readInstrs M.empty 0 . map (splitOn (`elem` "[,]: ")) $ inlines
regs0 = M.fromList $ zip [0..] [0, 0, 0, 0, 0, 0]
-- -------------------------------------------------------------------
findCycle seen (value1 : value2 : values)
| (elem) value2 seen = value1
| otherwise = findCycle (value2 : seen) (value2 : values)
-- answer part two: 12333799
solve1821_2 _ =
findCycle [] $ loop21 (0 :: Int) (0 :: Int)
where
loop21 r2 r3 =
(r3_2 : loop21 r2_2 r3_2)
where
(r2_1) = r3 .|. 0x10000
(r2_2, r3_2) = loop22 r2_1 0x1553d2
loop22 r2 r3
| r2 < 256 = (r2, r3_1)
| otherwise = loop22 r2_1 r3_1
where
r3_1 = (((r3 + (r2 .&. 0xff)) * 0x1016b) .&. 0xffffff)
r2_1 = (div) r2 256
-- -------------------------------------------------------------------
-- seen = set()
-- r2 = r3 = 0
-- while True:
-- r2 = r3 | 0x10000
-- r3 = 0x1553d2
-- while True:
-- r3 = (((r3 + (r2 & 0xff)) * 0x1016b) & 0xffffff)
-- if r2 < 256: break
-- r2 = r2 / 256
-- if r3 in seen: print r3, len(seen); exit(0)
-- seen.add(r3)
-- print r3
-- if r3 == 0: break # VAL
-- # unsigned long long r0, r2, r3;
-- # int main(void) {
-- # r3 = 0;
-- # do {
-- # r2 = r3 | 0x10000;
-- # r3 = 0x1553d2;
-- # do {
-- # r3 = r3 + (r2 & 0xff);
-- # r3 = r3 & 0xffffff;
-- # r3 = r3 * 0x1016b;
-- # r3 = r3 & 0xffffff;
-- # if (r2 < 256) break;
-- # r2 = r2 / 256;
-- # }
-- # while (1);
-- # printf("%llu\n", r3); // return 1;
-- # }
-- # while (r3 != r0);
-- # return 0;
-- # }
-- 00 seti 123 0 3 r3 <- 123
-- 01 ! bani 3 456 3 r3 <- r3 & 456
-- 02 eqri 3 72 3 r3 <- r3 == 72
-- 03 x addr 3 4 4 pc <- pc + r3
-- 04 x seti 0 0 4 pc <- 0
--
-- 05 seti 0 2 3 r3 <- 0
--
-- 06 ! bori 3 65536 2 r2 <- r3 | 65536
-- 07 seti 1397714 1 3 r3 <- 1397714
--
-- 08 ! bani 2 255 5 r5 <- r2 & 255
-- 09 addr 3 5 3 r3 <- r3 + r5
-- 10 bani 3 16777215 3 r3 <- r3 & 16777215
-- 11 muli 3 65899 3 r3 <- r3 * 65899
-- 12 bani 3 16777215 3 r3 <- r3 & 16777215
-- 13 gtir 256 2 5 r5 <- 256 > r2
-- 14 x addr 5 4 4 pc <- pc + r5
-- 15 x addi 4 1 4 pc <- pc + 1
-- 16 x seti 27 6 4 pc <- 27
-- 17 seti 0 6 5 r5 <- 0
--
-- 18 ! addi 5 1 1 r1 <- r5 + 1
-- 19 muli 1 256 1 r1 <- r1 * 256
-- 20 gtrr 1 2 1 r1 <- r1 > r2
-- 21 x addr 1 4 4 pc <- pc + r1
-- 22 x addi 4 1 4 pc <- pc + 1
-- 23 x seti 25 2 4 pc <- 25
-- 24 ! addi 5 1 5 r5 <- r5 + 1
-- 25 x seti 17 0 4 pc <- 17
-- 26 ! setr 5 7 2 r2 <- r5
-- 27 x seti 7 4 4 pc <- 7
--
-- 28 ! eqrr 3 0 5 r5 <- r3 == r0
-- 29 x addr 5 4 4 pc <- pc + r5
-- 30 x seti 5 8 4 pc <- 5
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
--
-- 2018 DAY 20
--
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
data RNode = RSt [Char] | RCh [[RNode]] deriving (Show)
-- get one node
-- "AA" -> RSt "AA", ""
-- "(AA|BB)" -> RCh [...], ""
-- "(AA|)" -> RCh [...], ""
getRNode str @ (x : xs)
| isLetter x = (RSt nd1, ftail)
| x == '(', n == ')' = (RCh nds, ntail)
| x == ')' = (RSt [], str)
| otherwise = undefined
where
(nd1, ftail) = span (flip notElem "(|)$") str
(nds, n : ntail) = getLNodes xs
-- get a list of nodes
-- "AA|BB" -> [RSt "AA"], "|BB"
-- "AA(CC)DD|BB" -> [RSt "AA", RCh [...], RSt "DD"], "|BB"
getRNodes str
| null str = ([], str)
| x == '|' || x == ')' = ([], str)
| x == '(' || isLetter x = (nd1 : ndx, ntail)
| otherwise = undefined
where
(x : _) = str
(nd1, ftail) = getRNode str
(ndx, ntail) = getRNodes ftail
-- get a list of list of nodes
-- "AA)" -> [[RSt "AA"]], ")"
-- "AA(CC)DD|CC" -> [[RSt "AA", RCh [...], RSt "DD"], [RSt "CC"]], ""
getLNodes str
| null ftail = (nd1 : [], ftail)
| n == ')' = (nd1 : [], ftail)
| n == '|' = (nd1 : ndx, ntail)
| otherwise = undefined
where
(nd1, ftail) = getRNodes str
(n : ns) = ftail
(ndx, ntail) = getLNodes ns
-- -------------------------------------------------------------------
-- COORD X STRING_NODE -> NEWMAP, COORD
strDest dmap (sx, sy) (c : cs)
| c == 'N' = strNext (sx, sy - 1) cs
| c == 'S' = strNext (sx, sy + 1) cs
| c == 'E' = strNext (sx + 1, sy) cs
| c == 'W' = strNext (sx - 1, sy) cs
where
newval = (M.findWithDefault 0 (sx, sy) dmap) + 1
newmap newcrd = M.insertWith min newcrd newval dmap
strNext newcrd = strDest (newmap newcrd) newcrd
strDest dmap (sx, sy) [] = (dmap, (sx, sy))
-- COORD_LIST X ONE_NODE -> NEWMAP, NEW_COORD_LIST
nodeDests (dmap, starts) (RSt n) =
foldl' (\(xmap, xcrds) crd ->
let (nmap, ncrd) = strDest xmap crd n
in (nmap, nub $ ncrd : xcrds)
) (dmap, []) starts
nodeDests (dmap, starts) (RCh l) =
foldl' (\(xmap, xcrds) ndl ->
let (nmap, ncrds) = nodesDests (xmap, starts) ndl
in (nmap, nub $ ncrds ++ xcrds)
) (dmap, []) l
-- -- COORD_LIST X NODE_LIST -> NEWMAP, NEW_COORD_LIST
nodesDests (dmap, starts) [] = (dmap, starts)
nodesDests (dmap, starts) (n : ns) =
nodesDests (nodeDests (dmap, starts) n) ns
-- -------------------------------------------------------------------
-- answer part one: 3465
solve1820_1 =
last . sort . M.elems .
-- distance map [((x, y), dist), ...]
fst . nodesDests (M.empty, [(0, 0)]) .
-- regnode list
fst . getRNodes . filter (flip elem "(NS|EW)")
-- -------------------------------------------------------------------
-- answer part two: 7956
solve1820_2 =
length . filter (>= 1000) . M.elems .
-- distance map [((x, y), dist), ...]
fst . nodesDests (M.empty, [(0, 0)]) .
-- regnode list
fst . getRNodes . filter (flip elem "(NS|EW)")
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
--
-- 2018 DAY 19
--
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
readInstrs imap n ((opcode : rs) : ls) =
readInstrs nmap (n + 1) ls
where
(r1 : r2 : r3 : []) = map toInt rs
(nmap) = (M.insert n (opcode, r1, r2, r3) imap)
readInstrs imap _ [] = imap
execProg regs ipr imap
| M.notMember pc imap = regs
| trace ((printf "%2d | %s %d %d %d | " pc opc ra rb rc) ++
(concat . map (printf "%6d") . M.elems $ regs)) False = undefined
| otherwise = execProg nregs ipr imap
where
pc = (M.!) regs ipr
(opc, ra, rb, rc) = (M.!) imap pc
iregs = execInstr regs opc ra rb rc
nregs = M.adjust (+1) ipr iregs
-- answer part one: 920
solve1819_1 input =
execProg regs0 ipr imap
where
(ipline : inlines) = lines $ input
ipr = toInt . last . words $ ipline
imap = readInstrs M.empty 0 . map (splitOn (`elem` "[,]: ")) $ inlines
regs0 = M.fromList $ zip [0..] [1, 0, 0, 0, 0, 0]
-- -------------------------------------------------------------------
-- answer part two: 11151360
solve1819_2 _ =
sum $ divisors 10551319
where divisors y = [ x | x <- [1..y], (((mod) y x) == 0) ]
-- solve1819_2 input =
-- execProg regs0 ipr imap
-- where
-- (ipline : inlines) = lines $ input
-- ipr = toInt . last . words $ ipline
-- imap = readInstrs M.empty 0 . map (splitOn (`elem` "[,]: ")) $ inlines
-- -- regs0 = M.fromList $ zip [0..] [1, 0, 0, 0, 0, 0]
-- -- regs0 = M.fromList $ zip [0..] [0, 1, 10551319, 5, 1, 10551319]
-- regs0 = M.fromList $ zip [0..] [1, 1, 10551319, 10, 2, 10551319]
-- -------------------------------------------------------------------
-- [ r0, r1, r2, r3, r4, r5 ]
-- [ SUM, tmp, VAL, PC, rX, rY ]
-- L03 mulr 4 5 1 tmp <- rX * rY
-- L04 eqrr 1 2 1 tmp <- tmp == VAL
-- L05 x addr 1 3 3 pc <- pc + tmp if (rX * rY) == VAL) goto L07
-- L06 x addi 3 1 3 pc <- pc + 1 goto L08
-- L07 addr 4 0 0 sum <- rx + sum sum <- rx + sum
-- L08 addi 5 1 5 ry <- ry + 1 ry <- ry + 1
-- L09 gtrr 5 2 1 tmp <- ry > val
-- L10 x addr 3 1 3 pc <- pc + tmp if (ry > val) goto L12
-- L11 x seti 2 1 3 pc <- 2 goto L03
-- -- L10 while (ry <= val)
-- -- L05 if (rX * rY) == VAL) -- if x divides VAL
-- -- L07 sum <- rx + sum -- -> add x to sum
-- -- L08 ry <- ry + 1
-- L12 addi 4 1 4 rx <- rx + 1 rx <- rx + 1
-- L13 gtrr 4 2 1 tmp <- rx > val
-- L14 x addr 1 3 3 pc <- pc + tmp if (rx > val) EXIT
-- L15 x seti 1 3 3 pc <- 1 goto LO2
-- L16 x mulr 3 3 3 pc <- END
-- L01 seti 1 8 4 rx <- 1
-- L02 seti 1 4 5 ry <- 1
-- -- L01 rx <- 1
-- -- L02 ry <- 1
-- --
-- -- L15 while (rx <= val)
-- --
-- -- L10 while (ry <= val)
-- -- L05 if (rX * rY) == VAL)
-- -- L07 sum <- rx + sum
-- -- L08 ry <- ry + 1
-- --
-- -- L12 rx <- rx + 1
-- ([0,2197581,10551319,4,1,2197581],("eqrr",1,2,1),[0,0,10551319,4,1,2197581])
-- ([0,0,10551319,5,1,2197581],("addr",1,3,3),[0,0,10551319,5,1,2197581])
-- ([0,0,10551319,6,1,2197581],("addi",3,1,3),[0,0,10551319,7,1,2197581])
-- ([0,0,10551319,8,1,2197581],("addi",5,1,5),[0,0,10551319,8,1,2197582])
-- ([0,0,10551319,9,1,2197582],("gtrr",5,2,1),[0,0,10551319,9,1,2197582])
-- ([0,0,10551319,10,1,2197582],("addr",3,1,3),[0,0,10551319,10,1,2197582])
-- ([0,0,10551319,11,1,2197582],("seti",2,1,3),[0,0,10551319,2,1,2197582])
-- ([0,0,10551319,3,1,2197582],("mulr",4,5,1),[0,2197582,10551319,3,1,2197582])
-- ([0,2197582,10551319,4,1,2197582],("eqrr",1,2,1),[0,0,10551319,4,1,2197582])
-- ([0,0,10551319,5,1,2197582],("addr",1,3,3),[0,0,10551319,5,1,2197582])
-- ([0,0,10551319,6,1,2197582],("addi",3,1,3),[0,0,10551319,7,1,2197582])
-- ([0,0,10551319,8,1,2197582],("addi",5,1,5),[0,0,10551319,8,1,2197583])
-- ([0,0,10551319,9,1,2197583],("gtrr",5,2,1),[0,0,10551319,9,1,2197583])
-- ([0,0,10551319,10,1,2197583],("addr",3,1,3),[0,0,10551319,10,1,2197583])
-- ([0,0,10551319,11,1,2197583],("seti",2,1,3),[0,0,10551319,2,1,2197583])
-- ([0,0,10551319,3,1,2197583],("mulr",4,5,1),[0,2197583,10551319,3,1,2197583])
-- ([0,2197583,10551319,4,1,2197583],("eqrr",1,2,1),[0,0,10551319,4,1,2197583])
-- ([0,0,10551319,5,1,2197583],("addr",1,3,3),[0,0,10551319,5,1,2197583])
-- ([0,0,10551319,6,1,2197583],("addi",3,1,3),[0,0,10551319,7,1,2197583])
-- ([0,0,10551319,8,1,2197583],("addi",5,1,5),[0,0,10551319,8,1,2197584])
-- ([0,0,10551319,9,1,2197584],("gtrr",5,2,1),[0,0,10551319,9,1,2197584])
-- ([0,0,10551319,10,1,2197584],("addr",3,1,3),[0,0,10551319,10,1,2197584])
-- ([0,0,10551319,11,1,2197584],("seti",2,1,3),[0,0,10551319,2,1,2197584])
-- --->>> [0,1,10551319,5,1,10551319]
-- ([1,0,10551319,3,2,91230],("mulr",4,5,1),[1,182460,10551319,3,2,91230])
-- ([1,182460,10551319,4,2,91230],("eqrr",1,2,1),[1,0,10551319,4,2,91230])
-- ([1,0,10551319,5,2,91230],("addr",1,3,3),[1,0,10551319,5,2,91230])
-- ([1,0,10551319,6,2,91230],("addi",3,1,3),[1,0,10551319,7,2,91230])
-- ([1,0,10551319,8,2,91230],("addi",5,1,5),[1,0,10551319,8,2,91231])
-- ([1,0,10551319,9,2,91231],("gtrr",5,2,1),[1,0,10551319,9,2,91231])
-- ([1,0,10551319,10,2,91231],("addr",3,1,3),[1,0,10551319,10,2,91231])
-- ([1,0,10551319,11,2,91231],("seti",2,1,3),[1,0,10551319,2,2,91231])
-- ([1,0,10551319,3,2,91231],("mulr",4,5,1),[1,182462,10551319,3,2,91231])
-- ([1,182462,10551319,4,2,91231],("eqrr",1,2,1),[1,0,10551319,4,2,91231])
-- ([1,0,10551319,5,2,91231],("addr",1,3,3),[1,0,10551319,5,2,91231])
-- ([1,0,10551319,6,2,91231],("addi",3,1,3),[1,0,10551319,7,2,91231])
-- ([1,0,10551319,8,2,91231],("addi",5,1,5),[1,0,10551319,8,2,91232])
-- ([1,0,10551319,9,2,91232],("gtrr",5,2,1),[1,0,10551319,9,2,91232])
-- ([1,0,10551319,10,2,91232],("addr",3,1,3),[1,0,10551319,10,2,91232])
-- ([1,0,10551319,11,2,91232],("seti",2,1,3),[1,0,10551319,2,2,91232])
-- ([1,0,10551319,3,2,91232],("mulr",4,5,1),[1,182464,10551319,3,2,91232])
-- ([1,182464,10551319,4,2,91232],("eqrr",1,2,1),[1,0,10551319,4,2,91232])
-- ([1,0,10551319,5,2,91232],("addr",1,3,3),[1,0,10551319,5,2,91232])
-- ([1,0,10551319,6,2,91232],("addi",3,1,3),[1,0,10551319,7,2,91232])
-- ([1,0,10551319,8,2,91232],("addi",5,1,5),[1,0,10551319,8,2,91233])
-- ([1,0,10551319,9,2,91233],("gtrr",5,2,1),[1,0,10551319,9,2,91233])
-- ([1,0,10551319,10,2,91233],("addr",3,1,3),[1,0,10551319,10,2,91233])
-- ([1,0,10551319,11,2,91233],("seti",2,1,3),[1,0,10551319,2,2,91233])
-- --->>> [1,1,10551319,10,2,10551320]
-- ([1,0,10551319,3,3,38081],("mulr",4,5,1),[1,114243,10551319,3,3,38081])
-- ([1,114243,10551319,4,3,38081],("eqrr",1,2,1),[1,0,10551319,4,3,38081])
-- ([1,0,10551319,5,3,38081],("addr",1,3,3),[1,0,10551319,5,3,38081])
-- ([1,0,10551319,6,3,38081],("addi",3,1,3),[1,0,10551319,7,3,38081])
-- ([1,0,10551319,8,3,38081],("addi",5,1,5),[1,0,10551319,8,3,38082])
-- ([1,0,10551319,9,3,38082],("gtrr",5,2,1),[1,0,10551319,9,3,38082])
-- ([1,0,10551319,10,3,38082],("addr",3,1,3),[1,0,10551319,10,3,38082])
-- ([1,0,10551319,11,3,38082],("seti",2,1,3),[1,0,10551319,2,3,38082])
-- ([1,0,10551319,3,3,38082],("mulr",4,5,1),[1,114246,10551319,3,3,38082])
-- ([1,114246,10551319,4,3,38082],("eqrr",1,2,1),[1,0,10551319,4,3,38082])
-- ([1,0,10551319,5,3,38082],("addr",1,3,3),[1,0,10551319,5,3,38082])
-- ([1,0,10551319,6,3,38082],("addi",3,1,3),[1,0,10551319,7,3,38082])
-- ([1,0,10551319,8,3,38082],("addi",5,1,5),[1,0,10551319,8,3,38083])
-- ([1,0,10551319,9,3,38083],("gtrr",5,2,1),[1,0,10551319,9,3,38083])
-- ([1,0,10551319,10,3,38083],("addr",3,1,3),[1,0,10551319,10,3,38083])
-- ([1,0,10551319,11,3,38083],("seti",2,1,3),[1,0,10551319,2,3,38083])
-- ([1,0,10551319,3,3,38083],("mulr",4,5,1),[1,114249,10551319,3,3,38083])
-- ([1,114249,10551319,4,3,38083],("eqrr",1,2,1),[1,0,10551319,4,3,38083])
-- ([1,0,10551319,5,3,38083],("addr",1,3,3),[1,0,10551319,5,3,38083])
-- ([1,0,10551319,6,3,38083],("addi",3,1,3),[1,0,10551319,7,3,38083])
-- ([1,0,10551319,8,3,38083],("addi",5,1,5),[1,0,10551319,8,3,38084])
-- ([1,0,10551319,9,3,38084],("gtrr",5,2,1),[1,0,10551319,9,3,38084])
-- ([1,0,10551319,10,3,38084],("addr",3,1,3),[1,0,10551319,10,3,38084])
-- ([1,0,10551319,11,3,38084],("seti",2,1,3),[1,0,10551319,2,3,38084])
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
--
-- 2018 DAY 18
--
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
showLCA lca =
(concat . map color) . concat . map ((:) '\n') $
[[area (x, y) | x <- [0 .. cmax]] | y <- [0 .. cmax]]
where
cmax = maximum . map fst . M.keys $ lca
area (x, y) = (M.!) lca (x, y)
--
color x
| x == '|' = printf "\ESC[1;32m\ \%c\ \\ESC[0;m" x
| x == '#' = printf "\ESC[1;31m\ \%c\ \\ESC[0;m" x
| otherwise = printf "%c" x
getLCA lca (x, y) (c : cs)
| elem c ".|#" = getLCA (M.insert (x, y) c lca) (x + 1, y) cs
| c == '\n' = getLCA (lca) (0, y + 1) cs
getLCA lca (_, _) ([]) = lca
nextVal lca ((x, y), c)
| c == '.', nbn '|' >= 3 = ((x, y), '|')
| c == '.' = ((x, y), c)
| c == '|', nbn '#' >= 3 = ((x, y), '#')
| c == '|' = ((x, y), c)
| c == '#', nbn '#' >= 1, nbn '|' >= 1 = ((x, y), '#')
| c == '#' = ((x, y), '.')
where
cmax = maximum . map fst . M.keys $ lca
area (x, y) = M.findWithDefault ' ' (x, y) lca
neighs = [area (nx, ny) | nx <- [x - 1 .. x + 1], ny <- [y - 1 .. y + 1], (nx, ny) /= (x, y)]
nbn c = length . filter (== c) $ neighs
nextLCA lca =
M.fromList . map (nextVal lca) . M.assocs $ lca
evolveLCA n lca
| trace (showLCA lca) False = undefined
| n == 0 = nbel '|' * nbel '#'
| otherwise = evolveLCA (n - 1) (nextLCA lca)
where nbel c = length . filter (== c) . M.elems $ lca
-- answer part one: 531417
solve1818_1 =
evolveLCA 10 . getLCA M.empty (0, 0)
-- -------------------------------------------------------------------
evolveLCX lmap n lca
| trace (showLCA lca) False = undefined
| M.member lca lmap =
evolveLCA ((mod) n (((M.!) lmap lca) - n)) (lca)
| otherwise = evolveLCX (M.insert lca n lmap) (n - 1) (nextLCA lca)
| n == 0 = undefined
-- answer part two: 205296
solve1818_2 =
evolveLCX M.empty 1000000000 . getLCA M.empty (0, 0)
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
--
-- 2018 DAY 17
--
-- -------------------------------------------------------------------
-- -------------------------------------------------------------------
showScan scan water (cx, cy) =
(concat . map color) . concat . (:) "\n" . intersperse "\n" $ [[cell (x, y) | x <- [xmin .. xmax]] | y <- [ymin .. ymax]]
where
(xmin, xmax) = (\l -> (minimum l, maximum l)) . map fst . M.keys $ scan
(ymin, ymax) = (\l -> (minimum l, maximum l)) . map snd . M.keys $ scan
sqrs (x, y) = M.findWithDefault '.' (x, y) scan
watr (x, y) = M.findWithDefault (sqrs (x, y)) (x, y) water
cell (x, y) = if (x == cx && y == cy) then '?' else watr (x, y)
--
color x
| (elem) x "+|~" = "\ESC[1;34m" ++ [x] ++ "\ESC[0;m"
| (elem) x "?" = "\ESC[1;31m" ++ [x] ++ "\ESC[0;m"
| otherwise = [x]
-- x=495, y=2..7
-- y=7, x=495..501
scanLine scan ((c1 : []) : c1s1 : (c2 : []) : c2s1 : c2s2 : [])
| c1 == 'x' = M.union (M.fromList [((c1v1, y), '#') | y <- [c2v1 .. c2v2]]) scan
| c1 == 'y' = M.union (M.fromList [((x, c1v1), '#') | x <- [c2v1 .. c2v2]]) scan
where (c1v1 : c2v1 : c2v2 : []) = map toInt [c1s1, c2s1, c2s2]
scanLine scan (_) = scan
-- TODO - very inefficient - cells tested way too often
waterflow scan water (x, y)
-- | trace ("\nFLOW " ++ (show (x, y)) ++ showScan scan water (x, y)) False = undefined
-- water below limits
| y > ymax = (True, newwater)
--
| otherwise =
let
(flowdown, waterdown)
| iswall (x, y + 1) = (False, newwater)
| isbackwater (x, y + 1) = (False, newwater)
| isflowing (x, y + 1) = (True, newwater)
| otherwise = waterflow scan newwater (x, y + 1)
(backwater) =
M.union (M.fromList $ zip ((M.keys waterdown) \\ (M.keys newwater)) (repeat '~')) newwater
-- flowing water on left/right may become dead
-- squares are tested just after being flooded
-- it should not block spreading on left/right
(flowleft, waterleft)
| iswall (x - 1, y) = (False, backwater)
| isbackwater (x - 1, y) = (False, backwater)
| isflowing (x - 1, y) = (False, backwater) -- XXX :-(
| otherwise = waterflow scan backwater (x - 1, y)
(flowright, waterright)
| iswall (x + 1, y) = (False, waterleft)
| isbackwater (x + 1, y) = (False, waterleft)
| isflowing (x + 1, y) = (False, waterleft) -- XXX :-(
| otherwise = waterflow scan waterleft (x + 1, y)
in
(
flowdown || flowleft || flowright,
if flowdown then waterdown else waterright
)
where
iswall (x, y) = M.findWithDefault '.' (x, y) scan == '#'
isflowing (x, y) = M.findWithDefault '?' (x, y) water == '|'
isbackwater (x, y) = M.findWithDefault '?' (x, y) water == '~'
--
newwater = M.insert (x, y) '|' water
ymax = maximum . map snd . M.keys $ scan
-- answer part one: 31383
solve1817_1 input
| trace (showScan scan water (500, 0)) False = undefined
| otherwise =
length . filter (\(_, y) -> y >= ymin && y <= ymax) . M.keys $ water
where
scan = foldl' (scanLine) M.empty . map (splitOn (flip (elem) "=,. ")) . lines $ input
water = snd $ waterflow scan M.empty (500, 0)
(ymin, ymax) = (\l -> (minimum l, maximum l)) . map snd . M.keys $ scan
-- (164.07 secs, 225,487,531,952 bytes)
-- -------------------------------------------------------------------
-- answer part two: 25376
solve1817_2 input
| trace (showScan scan water (500, 0)) False = undefined