Boxcar
; Day 4: Perilous Pier
[ define colors [ chars "roygbv" ]]
; Whether `p` instructions on repeat can print `barcode` (a list of colors).
;
; Position `i` is printed by instruction `[mod i p]`, so each color needs its
; own set of instructions: no two colors' sets can overlap.
[ define fits
[ fn [ barcode p ]
[ train colors
[ map [ fn [ c ] [ train [ indices-of barcode c ] [ map [ fn [ i ] [ mod i p ]]]]]]
[ pairs ]
[ map [ fn [{ a b }] [ intersect a b ]]]
[ concat ]
[ count ]
[ = 0 ]]]]
; The fewest instructions that print `barcode`.
;
; As many instructions as the barcode is long always fits, so there is always
; one to find.
[ define instructions
[ fn [ barcode ]
[ train barcode [ enumerate ]
[ find [ fn [{ i _ }] [ fits barcode [ + i 1 ]]]]
[ fn [{ i _ }] [ + i 1 ]]]]]
[ part 1
[ train input [ lines ] [ map chars ] [ map instructions ] [ fold + 0 ]]]
[ part 2
; The whole document is one barcode, without the newlines.
[ train input [ lines ] [ map chars ] [ concat ] [ instructions ]]]
[ tests
[ example puzzle [ include "input.txt" ] [ part 1 8027 ] [ part 2 1696 ]]
[ example example "
rgbrgbrgbr
?rv
o??v???y
??bg?v??
??b?????
???
" [ part 1 16 ]]
[ example repeating "rgbrgbrgbr" [ part 1 3 ]]
[ example short "?rv" [ part 1 2 ]]
[ example sparse "o??v???y" [ part 1 5 ]]
[ example middle "??bg?v??" [ part 1 4 ]]
[ example single "??b?????" [ part 1 1 ]]
[ example illegible "???" [ part 1 1 ]]
[ example document "
rro??
?g
?g???
??r?????
??g?
??
yy?v?o
???v
b?g??
?y??v?or
????r?o
??
?????
?r??v?r
" [ part 2 16 ]]]