AoC'21, day 5, second problem rvc


Second, throw in diagonal lines.

 $ cat 05b.rkt  
 #lang racket 
  
  
 (require 
   (prefix-in aoc05: "05a.rkt") 
   (prefix-in utl: "../scheme/utl.rkt")) 
  
  
 (define (aoc05b . args) 
  
   ; Return the number of deep vent points in the given sea-floor 
   ; map.  If no map is given, use the contest problem input; 
   ; otherwise assume the argument is the string representation of 
   ; a problem input. 
  
   (deep-vent-point-count 
     (apply aoc05:read-input args))) 
  
  
  
 (define (deep-vent-point-count sea-floor-map) 
  
   ; Return the number of deep vent points in the given sea-floor 
   ; map.  A vent point is deep when it belongs to more than one 
   ; vent. 
  
  
   (define (delta c1 c2) 
  
     ; Return the delta that steps from the first given value to 
     ; the second. 
  
     (utl:signum (- c2 c1))) 
  
  
   (define plotted-points (make-hash)) 
  
  
   (define (plot-point x y) 
  
     ; Add the point with the given coordinates to the points 
     ; plotted. 
  
     (let ((pt (list x y))) 
       (hash-set! plotted-points pt 
                  (+ (hash-ref plotted-points pt 0) 1)))) 
  
  
   (define (plot-line ep1 ep2) 
  
     ; Plot the points on the line from the first given coordinate 
     ; to the second (inclusive at both ends). 
  
     (let* ((x1 (car ep1)) 
            (y1 (cadr ep1)) 
            (x2 (car ep2)) 
            (y2 (cadr ep2)) 
            (delta-x (delta x1 x2)) 
            (delta-y (delta y1 y2))) 
  
       (do 
  
         ((x x1 (+ x delta-x)) 
          (y y1 (+ y delta-y)) 
          (n (+ (max (abs (- x2 x1)) (abs (- y2 y1))) 1) (- n 1))) 
            
         ((zero? n) #t) 
  
         (plot-point x y)))) 
  
  
   (for-each 
     (lambda (l) (plot-line (car l) (cadr l))) 
     sea-floor-map) 
  
   (foldl 
     (lambda (c s) (+ s (if (= c 1) 0 1))) 
     0 
     (hash-values plotted-points))) 
  
  
 (module+ main 
  
   (aoc05b)) 
  
  
 (define example-result 12) 
  
  
 (module+ test 
  
   (require rackunit) 
  
   (for-each 
  
     (lambda (p) (check-equal? (aoc05b (car p)) (cdr p))) 
  
     `(("0,0 -> 3,0" . 0) 
       ("0,0 -> 3,0\n0,0 -> 3,0" . 4) 
       ("0,0 -> 3,3\n0,0 -> 3,3" . 4) 
       ("0,0 -> 4,4\n4,0 -> 0,4" . 1) 
       ("0,0 -> 3,0\n3,0 -> 3,3\n3,3 -> 0,3\n0,3 -> 0,0" . 4) 
       (,aoc05:example-data . ,example-result))) 
  
   (check-equal? (aoc05b) 17882)) 
  
 $ raco test 05b.rkt  
 raco test: (submod "05b.rkt" test) 
 7 tests passed 
  
 $