sol.scm (1833B) [raw]
1 #!/usr/local/bin/chicken-csi -ss 2 (import (chicken string) 3 (chicken io)) 4 5 (define (parse-line l) 6 (let ((parts (string-split l))) 7 (cond ((equal? (car parts) "noop") 8 (list (string->symbol (car parts)))) 9 ((equal? (car parts) "addx") 10 (list (string->symbol (car parts)) 11 (string->number (cadr parts)))) 12 (else "Error: bad line" l)))) 13 14 (define (simul cmds) 15 (let loop ((cmds cmds) (x 1)) 16 (if (null? cmds) 17 '() 18 (let ((cmd (car cmds))) 19 (cond ((eq? (car cmd) 'noop) 20 (cons x (loop (cdr cmds) x))) 21 ((eq? (car cmd) 'addx) 22 ; takes 2 counts, so append x THEN append x + val 23 (let ((x2 (+ (cadr cmd) x))) 24 (cons x (cons x2 (loop (cdr cmds) x2))))) 25 (else "Bad cmd " cmd)))))) 26 27 ; x is 3-wide, covers (x - 1, x, x + 1), (x + 39 , x + 40, x + 41), ... 28 (define (overlaps? x c) 29 ; NOTE: need to add 1 to X since cycle is 1 indexed 30 (>= 1 (abs (- (add1 x) (modulo c 40))))) 31 32 (define (part-1 sim) 33 (let loop ((i 1) (sim sim) (count 0)) 34 ; (print (list i (car sim) count)) 35 (if (null? sim) 36 count 37 (if (= 0 (modulo (+ i 20) 40)) 38 (loop (add1 i) (cdr sim) (+ count (* i (car sim)))) 39 (loop (add1 i) (cdr sim) count))))) 40 41 (define (part-2 sim) 42 (let loop ((i 0) (sim sim)) 43 (if (null? sim) 44 'done 45 (begin 46 (and (= 0 (modulo i 40)) (newline)) 47 (if (overlaps? (car sim) (add1 i)) 48 (display "#") 49 (display " ")) 50 (loop (add1 i) (cdr sim)))))) 51 52 (define (main args) 53 (let* ((lines (read-lines)) 54 (cmds (map parse-line lines)) 55 (x-vals (cons 1 (simul cmds)))) ; NOTE: need first val 56 (print (part-1 x-vals)) 57 (part-2 x-vals)))