! day ten ! from day 4 solution: ! : iterate-through-everything ( ... grid quot: ( ... x y grid -- ... ) -- ... ) over first length [ -rot over length [ -roll call ] 3with each-integer ] 2with each-integer ; inline ! : at-coord ( x y grid -- val ) swapd nth nth ; ! : valid-grid-index ( x y grid -- x y grid ? ) [ tuck [ length [ < ] [ drop 0 >= ] 2bi and ] [ first length [ < ] [ drop 0 >= ] 2bi and ] 2bi* and ] 3check ; ! from day 8 solution: ! : by-cols ( grid -- cols ) [ first length ] keep [ [ nth ] with map ] curry map-integers ; : trailhead-coords ( grid -- coords ) [ [ 2dup ] dip at-coord 0 = [ 2array ] [ 2drop f ] if ] collector [ iterate-through-everything ] dip sift >array ; : surrounding-squares ( x y grid -- squares ) [ { [ [ 1 + ] 2dip valid-grid-index [ drop 2array ] [ 3drop f ] if ] [ [ 1 - ] 2dip valid-grid-index [ drop 2array ] [ 3drop f ] if ] [ [ 1 + ] dip valid-grid-index [ drop 2array ] [ 3drop f ] if ] [ [ 1 - ] dip valid-grid-index [ drop 2array ] [ 3drop f ] if ] } 3cleave ] output>array sift ; ! x y grid square : surrounding-valid-squares ( x y grid -- squares ) 3dup surrounding-squares [ over [ first2 ] dip at-coord 1 - [ at-coord ] dip = ] 2with with filter ; : valid-squares? ( x y grid -- ? ) surrounding-valid-squares length 0 > ; : not-on-nine? ( x y grid -- ? ) at-coord 9 < ; : (do-trail) ( x y grid -- final-coords ) 3dup [ valid-squares? ] [ not-on-nine? ] 3bi and [ [ surrounding-valid-squares ] keep [ [ first2 ] dip (do-trail) ] curry map concat ] [ [ 2dup ] dip not-on-nine? [ 2drop { } ] [ 2array 1array ] if ] if ; : do-trail ( x y grid -- final-coords ) (do-trail) { } [ over [ index ] keepd swap [ drop ] [ suffix ] if ] reduce ; : parse-day-ten-input ( string -- grid ) split-lines harvest by-cols [ [ 1string dec> ] map ] map ; : solve-day-ten ( grid -- total-trailhead-count ) [ trailhead-coords ] keep [ [ first2 ] dip do-trail ] curry map concat length ; : solve-day-ten-part-two ( grid -- total-trailhead-count ) [ trailhead-coords ] keep [ [ first2 ] dip (do-trail) ] curry map concat length ;