master
Matthew Butterick 7 years ago
parent bbfca5f2a4
commit f85815ea65

@ -6,32 +6,28 @@
(define lines (port->lines port)) (define lines (port->lines port))
(strip-context #`(module mod "main.rkt" (strip-context #`(module mod "main.rkt"
#,@(for/list ([datum (in-port read (open-input-string (car lines)))]) #,@(for/list ([datum (in-port read (open-input-string (car lines)))])
datum) datum)
#,@(cdr lines)))) #,@(cdr lines))))
(define-macro (#%mb STARS LINE ...) (define-macro (#%mb STARS LINE ...)
#'(#%module-begin #'(#%module-begin
(time (STARS (list LINE ...))))) (time (STARS (list LINE ...)))))
(define (populate-hash! chars lines)
(for* ([(line lidx) (in-indexed lines)]
[(c cidx) (in-indexed (string->list line))]
#:unless (char=? c #\space))
(hash-set! chars (+ lidx (* +i cidx)) c)))
(define (traverse lines #:count-steps [count-steps? #f]) (define (traverse lines #:count-steps [count-steps? #f])
(define chars (make-hasheqv)) (define chars (for*/hasheqv ([(line lidx) (in-indexed lines)]
(populate-hash! chars lines) [(c cidx) (in-indexed (string->list line))]
#:unless (char=? c #\space))
(values (+ lidx (* +i cidx)) c)))
(define start (for/first ([k (in-hash-keys chars)] (define start (for/first ([k (in-hash-keys chars)]
#:when (zero? (real-part k))) #:when (zero? (real-part k)))
k)) k))
(define down 1) (define up -1) (define left -i) (define right +i) (define down 1) (define up -1) (define left -i) (define right +i)
(let loop ([here start][dir down][path null]) (let loop ([here start][dir down][path null])
(define here-char (hash-ref chars here #f)) (define here-char (hash-ref chars here #f))
(cond (cond
[here-char [here-char
(define next-dir (if (char=? here-char #\+) (define next-dir (if (char=? here-char #\+)
(if (hash-has-key? chars (+ here (* dir +i))) (* dir +i) (* dir -i)) (if (hash-has-key? chars (+ here (* dir right))) (* dir right) (* dir left))
dir)) dir))
(loop (+ here next-dir) next-dir (cons here-char path))] (loop (+ here next-dir) next-dir (cons here-char path))]
[count-steps? (length path)] [count-steps? (length path)]