Refactored Day 11 for performance.

This commit is contained in:
Jonathan Chan 2020-12-11 11:02:08 -08:00
parent 5a0a4f002b
commit 7649d689b6
1 changed files with 22 additions and 15 deletions

View File

@ -1,20 +1,13 @@
#lang curly-fn racket
(require "../lib.rkt")
(require threading
"../lib.rkt")
(define input (lists->vectors (map string->list (problem-input 11))))
(define width (vector-length (vector-ref input 0)))
(define length (vector-length input))
(define (neighbours seats r c)
(count
#{char=? % #\#}
(for*/list ([r* (in-range (max 0 (sub1 r)) (min (+ r 2) length))]
[c* (in-range (max 0 (sub1 c)) (min (+ c 2) width))]
#:unless (and (= r r*) (= c c*)))
(vector-ref (vector-ref seats r*) c*))))
(define (visible-in seats r c dr dc)
(define (first-seat r c dr dc)
(define rs
(cond
[(positive? dr) (in-range r length dr)]
@ -28,13 +21,27 @@
(for/or ([r* rs]
[c* cs]
#:unless (and (= r r*) (= c c*)))
(define seat (vector-ref (vector-ref seats r*) c*))
#:final (member seat '(#\L #\#))
(char=? seat #\#)))
(define seat (vector-ref (vector-ref input r*) c*))
(and (member seat '(#\L #\#))
(list r* c*))))
(define first-seats
(for*/hash ([r (in-range 0 length)]
[c (in-range 0 width)])
(values (list r c)
(filter-map (match-lambda [`(,dr ,dc) (first-seat r c dr dc)])
'((-1 -1) (-1 0) (-1 1) (0 -1) (0 1) (1 -1) (1 0) (1 1))))))
(define (neighbours seats r c)
(for*/sum ([r* (in-range (max 0 (sub1 r)) (min (+ r 2) length))]
[c* (in-range (max 0 (sub1 c)) (min (+ c 2) width))]
#:unless (and (= r r*) (= c c*)))
(if (char=? (vector-ref (vector-ref seats r*) c*) #\#) 1 0)))
(define (visible seats r c)
(count (match-lambda [`(,dr ,dc) (visible-in seats r c dr dc)])
'((-1 -1) (-1 0) (-1 1) (0 -1) (0 1) (1 -1) (1 0) (1 1))))
(count
(match-lambda [`(,r* ,c*) (char=? (vector-ref (vector-ref seats r*) c*) #\#)])
(hash-ref first-seats (list r c))))
(define (step-seats counter die seats)
(let ([new-seats (vector-map vector-copy (vector-copy seats))])