sol.scm (1329B) [raw]
1 #!/usr/local/bin/chicken-csi -ss 2 (import (chicken io) 3 (chicken string)) 4 5 ;; part 1: find full overlaps between pairs 6 ;; that means just count where for a-b,x-y a<x and y<b (or vice versa) 7 ;; (no need to check x<b since implied by x<y) 8 (define (overlaps? pair) 9 (let ((a (caar pair)) 10 (b (cadar pair)) 11 (x (caadr pair)) 12 (y (cadadr pair))) 13 (or 14 (and (<= a x) (>= b y)) 15 (and (<= x a) (>= y b))))) 16 17 ; part 2: no overlap: a > y or x > b 18 (define (any-overlap? pair) 19 (let ((a (caar pair)) 20 (b (cadar pair)) 21 (x (caadr pair)) 22 (y (cadadr pair))) 23 (not (or (> a y) (> x b))))) 24 25 (define (parse-line l) 26 (let* ((ranges (string-split l ",")) 27 (pair (map (lambda (r) 28 (map (lambda (x) (string->number x)) 29 (string-split r "-"))) 30 ranges))) 31 pair)) 32 33 (define (filter pred lst) 34 (cond ((null? lst) '()) 35 ((pred (car lst)) 36 (cons (car lst) (filter pred (cdr lst)))) 37 (else (filter pred (cdr lst))))) 38 39 (define (part-1 pairs) 40 (length (filter overlaps? pairs))) 41 42 (define (part-2 pairs) 43 (length (filter any-overlap? pairs))) 44 45 (define (main args) 46 (let* ((lines (read-lines)) 47 (pairs (map parse-line lines))) 48 (print (part-1 pairs)) 49 (print (part-2 pairs))))