AoC'21, day 2, first problem rvc


Move around on a 2D plane, return the resulting x*y.

 $ cat 02a.rkt  
 #lang racket 
  
  
 (provide 
   example-data 
   read-input) 
  
  
 (require 
   (prefix-in aoc: "aoc.rkt")) 
  
  
 (define (aoc02a . 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 read-input input))) 
  
  
 (define (navigate instructions) 
  
   ; Return the product of the depth and distance after following 
   ; the given navigation instructions. 
  
  
   (define funs 
     (hash 
       "forward" (lambda (x dd) (cons (car dd) (+ (cdr dd) x))) 
       "down"    (lambda (x dd) (cons (+ (car dd) x) (cdr dd))) 
       "up"      (lambda (x dd) (cons (- (car dd) x) (cdr dd))))) 
  
  
   (define dd 
     (foldl 
  
       (lambda (i dd) 
         ((hash-ref funs (car i)) (cadr i) dd)) 
  
       (cons 0 0) 
  
       instructions)) 
  
  
   (* (car dd) (cdr dd))) 
  
  
 (define  (read-input . input) 
  
   ; Return 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. 
  
   (map 
     (lambda (ni) (list (car ni) (string->number (cadr ni)))) 
     (car (aoc:aoc-read-input (if (null? input) 2 (car input)))))) 
  
  
 (module+ main 
  
   (aoc02a)) 
  
  
 (aoc:define-string example-data 
   "forward 5" 
   "down 5" 
   "forward 8" 
   "up 3" 
   "down 8" 
   "forward 2") 
  
 (define example-result (* 10 15)) 
  
  
 (module+ test 
  
   (require rackunit) 
  
   (check-equal? (aoc02a example-data) example-result) 
   (check-equal? (aoc02a) 1690020)) 
  
  
 $ raco test 02a.rkt  
 raco test: (submod "02a.rkt" test) 
 2 tests passed 
  
 $