sol.scm (2946B) [raw]
1 #!/usr/local/bin/chicken-csi -ss 2 (import (chicken string) 3 (chicken io)) 4 5 (define (char->digit c) 6 (- (char->integer c) 48)) 7 8 (define (lines->grid lines) 9 (let* ((vecs (map (lambda (l) (list->vector (map char->digit l))) 10 (map string->list lines)))) 11 (list->vector vecs))) 12 13 (define (grid-get grid r c) 14 (vector-ref (vector-ref grid r) c)) 15 16 (define (neg? x) (< x 0)) 17 18 (define (max-in-dir? grid r c dr dc) 19 (let ((tree (grid-get grid r c)) 20 (n (vector-length grid))) 21 (let loop ((r r) (c c)) 22 (let ((nr (+ r dr)) (nc (+ c dc))) 23 (if (or (neg? nr) (neg? nc) 24 (>= nr n) (>= nc n)) 25 #t ; made it off the map 26 (and (> tree (grid-get grid nr nc)) 27 (loop nr nc))))))) 28 29 (define (is-visible? grid r c) 30 ; (print "visiting " r " " c) 31 (let ((n (sub1 (vector-length grid)))) 32 (if (or (equal? r 0) (equal? c 0) 33 (equal? r n) (equal? c n)) 34 #t 35 (or (max-in-dir? grid r c 0 1) 36 (max-in-dir? grid r c 1 0) 37 (max-in-dir? grid r c -1 0) 38 (max-in-dir? grid r c 0 -1))))) 39 40 (define (num-in-dir grid r c dr dc) 41 (let ((tree (grid-get grid r c)) 42 (n (vector-length grid))) 43 (let loop ((r r) (c c) (count 0)) 44 (let ((nr (+ r dr)) (nc (+ c dc))) 45 (if (or (neg? nr) (neg? nc) 46 (>= nr n) (>= nc n)) 47 count ; made it off the map 48 (if (<= tree (grid-get grid nr nc)) 49 (add1 count) 50 (loop nr nc (add1 count)))))))) 51 52 (define (score grid r c) 53 ; (print "visiting " r " " c) 54 (apply * 55 (filter (lambda (x) (> x 0)) 56 (list (num-in-dir grid r c 0 1) 57 (num-in-dir grid r c 1 0) 58 (num-in-dir grid r c -1 0) 59 (num-in-dir grid r c 0 -1))))) 60 61 (define (range n) 62 (if (equal? n 0) 63 '(0) 64 (append (range (sub1 n)) (list n)))) 65 66 (define (filter pred lst) 67 (if (null? lst) 68 '() 69 (if (pred (car lst)) 70 (cons (car lst) (filter pred (cdr lst))) 71 (filter pred (cdr lst))))) 72 73 (define (count-visible grid) 74 (let ((n (sub1 (vector-length grid)))) 75 (let rloop ((r 0) (count 0)) 76 (if (> r n) 77 count 78 (rloop (add1 r) 79 (+ count (length (filter (lambda (c) (is-visible? grid r c)) 80 (range n))))))))) 81 82 (define (best-view grid) 83 (let ((n (sub1 (vector-length grid)))) 84 (apply max (map (lambda (r) 85 (apply max (map (lambda (c) (score grid r c)) (range n)))) 86 (range n))))) 87 88 (define (main args) 89 (let* ((lines (read-lines)) 90 (grid (lines->grid lines))) 91 (print (count-visible grid)) 92 (print (best-view grid)))) 93 94 ;; for repl exploration 95 (define gd '#(#(3 0 3 7 3) 96 #(2 5 5 1 2) 97 #(6 5 3 3 2) 98 #(3 3 5 4 9) 99 #(3 5 3 9 0)))