Skip to content

Instantly share code, notes, and snippets.

@qookei
Created December 12, 2023 00:37
Show Gist options
  • Save qookei/d4ee40d29182794b784d13e5390fea3b to your computer and use it in GitHub Desktop.
Save qookei/d4ee40d29182794b784d13e5390fea3b to your computer and use it in GitHub Desktop.
(use-modules (ice-9 textual-ports) (srfi srfi-1) (srfi srfi-26)
(ice-9 format) (ice-9 match) (ice-9 pretty-print))
(define (%read-input)
(let ([line (get-line (current-input-port))])
(if (eof-object? line)
'()
(cons (list->vector (string->list line))
(%read-input)))))
(define (read-input)
(list->vector (%read-input)))
(define (%get-column input x)
(let next ([y 0]
[items '()])
(if (eqv? y (vector-length input))
items
(next (1+ y)
(cons (vector-ref (vector-ref input y) x)
items)))))
(define (empty-cols input)
(let next ([x 0]
[cols '()])
(cond
[(eqv? x (vector-length (vector-ref input 0))) cols]
[(any (cut char=? #\# <>) (%get-column input x)) (next (1+ x) cols)]
[else (next (1+ x) (cons x cols))])))
(define (empty-rows input)
(let next ([y 0]
[rows '()])
(cond
[(eqv? y (vector-length input)) rows]
[(any (cut char=? #\# <>) (vector->list (vector-ref input y))) (next (1+ y) rows)]
[else (next (1+ y) (cons y rows))])))
(define (find-all-galaxies input multiplier)
(let ([empty-rows (empty-rows input)]
[empty-cols (empty-cols input)]
[width (vector-length (vector-ref input 0))]
[height (vector-length input)])
(let next ([x 0]
[y 0]
[galaxies '()])
(if (eqv? y height)
galaxies
(next (if (eqv? (1+ x) width) 0 (1+ x))
(if (eqv? (1+ x) width) (1+ y) y)
(if (char=? #\# (vector-ref (vector-ref input y) x))
(cons (cons (+ x (* multiplier (length (filter (cut > x <>) empty-cols))))
(+ y (* multiplier (length (filter (cut > y <>) empty-rows)))))
galaxies)
galaxies))))))
(define (part-common input multiplier)
(let ([galaxies (find-all-galaxies input multiplier)])
(/ (fold + 0
(map
(λ (galaxy1)
(fold + 0
(map
(λ (galaxy2)
(if (eqv? galaxy1 galaxy2)
0
(+ (abs (- (car galaxy1) (car galaxy2)))
(abs (- (cdr galaxy1) (cdr galaxy2))))))
galaxies)))
galaxies))
2)))
(let ([input (read-input)])
(format #t "Part 1: ~a~%" (part-common input 1))
(format #t "Part 2: ~a~%" (part-common input 999999)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment