Day 3: Gear Ratios


Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ or pastebin (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


🔒This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots

🔓 Edit: Post has been unlocked after 11 minutes

  • Andy
    link
    fedilink
    arrow-up
    2
    ·
    edit-2
    11 months ago

    Factor on github (with comments and imports):

    : symbol-indices ( line -- seq )
      [ ".0123456789" member? not ] find-all [ first ] map
    ;
    
    : num-spans ( line -- seq )
      >array [ over digit? [ nip ] [ 2drop f ] if ] map-index
      { f } split harvest
      [ [ first ] [ last ] bi 2array ] map
    ;
    
    : adjacent? ( num-span symbol-indices -- ? )
      swap [ first 1 - ] [ last 1 + ] bi [a,b]
      '[ _ interval-contains? ] any?
    ;
    
    : part-numbers ( line nearby-symbol-indices -- seq )
      [ dup num-spans ] dip
      '[ _ adjacent? ] filter
      swap '[ first2 1 + _ subseq string>number ] map
    ;
    
    : part1 ( -- )
      "vocab:aoc-2023/day03/input.txt" utf8 file-lines
      [ [ symbol-indices ] map ] keep
      [
        pick swap [ 1 - ?nth-of ] [ nth-of ] [ 1 + ?nth-of ] 2tri
        3append part-numbers sum
      ] map-index sum nip .
    ;
    
    : star-indices ( line -- seq )
      [ CHAR: * = ] find-all [ first ] map
    ;
    
    : gears ( line prev-line next-line -- seq-of-pairs )
      pick star-indices
      [ 1array '[ _ part-numbers ] [ 3dup ] dip tri@ 3append ]
      [ length 2 = ] map-filter [ 3drop ] dip
    ;
    
    : part2 ( -- )
      "vocab:aoc-2023/day03/input.txt" utf8 file-lines
      dup [
        pick swap [ 1 - ?nth-of ] [ 1 + ?nth-of ] 2bi
        gears [ product ] map-sum
      ] map-index sum nip .
    ;