AoC'21, day 2, second problem rvc


Same as the first problem, except moving up and down is more complicated.

 $ cat 02b.rkt  
 #lang racket 
  
  
 (require 
   (prefix-in aoc02: "02a.rkt") 
   (prefix-in aoc: "aoc.rkt")) 
  
  
 (define (aoc02b . input) 
  
   ; Return the product of the depth and distance after following 
   ; the given navigation instructions.  If no instructions are 
   ; given, use the contest problem input; otherwise assume the 
   ; argument is the string representation of a problem input. 
  
   (navigate 
     (apply aoc02:read-input input))) 
  
  
 (define (navigate instructions) 
  
   ; Return the product of the depth and distance after following 
   ; the given navigation instructions. 
  
  
   (struct location (aim depth distance) #:mutable) 
  
  
   (define funs 
     (hash 
  
      "forward" 
        (lambda (x lcn) 
          (set-location-distance! lcn (+ (location-distance lcn) x)) 
          (set-location-depth! lcn 
            (+ (location-depth lcn) (* (location-aim lcn) x))) 
          lcn) 
  
      "down" 
        (lambda (x lcn) 
          (set-location-aim! lcn (+ (location-aim lcn) x)) 
          lcn) 
  
      "up" 
        (lambda (x lcn) 
          (set-location-aim! lcn (- (location-aim lcn) x)) 
          lcn))) 
  
  
   (define lcn 
     (foldl 
  
       (lambda (i lcn) 
         ((hash-ref funs (car i)) (cadr i) lcn)) 
  
       (location 0 0 0) 
  
       instructions)) 
  
  
   (* (location-depth lcn) (location-distance lcn))) 
  
  
 (module+ main 
  
   (aoc02b)) 
  
  
 (define example-result (* 60 15)) 
  
  
 (module+ test 
  
   (require rackunit) 
  
   (check-equal? (aoc02b aoc02:example-data) example-result) 
   (check-equal? (aoc02b) 1408487760)) 
  
 $ raco test 02b.rkt 
 raco test: (submod "02b.rkt" test) 
 2 tests passed 
  
 $