You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
aoc-racket/2016/day01.rkt

55 lines
2.0 KiB
Racket

8 years ago
#lang br/quicklang
8 years ago
(define (read-syntax path port)
(define turn-strings (string-split (port->string port) ","))
(define turn-pattern #px"^([LR])(\\d+)$")
(define turn-datums
(for*/list ([tstr (in-list turn-strings)])
(define match-result (regexp-match turn-pattern (string-trim tstr)))
`(turn ,@(cdr (or match-result empty)))))
(strip-bindings
#`(module day01-mod "day01.rkt"
#,@turn-datums)))
(module+ reader (provide read-syntax))
8 years ago
(define-macro (mb . TURNS)
#'(#%module-begin
(solve . TURNS)))
(provide (rename-out [mb #%module-begin]))
8 years ago
(define (loc-dist loc)
8 years ago
(+ (abs (imag-part loc)) (abs (real-part loc))))
8 years ago
8 years ago
(struct $turn (rot dist) #:transparent)
(define rotate-left +i)
(define rotate-right -i)
(define same-dir 1)
8 years ago
(define (solve . turns)
8 years ago
(define found-twice-visited-loc #f)
8 years ago
(define north 0+1i)
8 years ago
(define starting-loc 0+0i)
(let loop ([locs (list starting-loc)] [dir north] [turns turns])
(cond
[(empty? turns)
(displayln (format "part 1 (dist of final location): ~a" (loc-dist (car locs))))]
[(zero? ($turn-dist (car turns))) (loop locs dir (cdr turns))]
[else
(define new-dir (* dir ($turn-rot (car turns))))
(define one-step 1)
(define new-loc (+ (car locs) (* new-dir one-step)))
(when (and (not found-twice-visited-loc) (member new-loc locs))
(set! found-twice-visited-loc new-loc)
(displayln (format "part 2 (dist of first twice-visited location): ~a"
(loc-dist new-loc))))
(define decremented-turn ($turn same-dir (sub1 ($turn-dist (car turns)))))
(loop (cons new-loc locs) new-dir (cons decremented-turn (cdr turns)))])))
8 years ago
(define-macro-cases turn
[(_ DIR DIST)
8 years ago
(with-pattern ([ENCODED-DIR (syntax-case #'DIR ()
8 years ago
["L" #'rotate-left]
["R" #'rotate-right])])
8 years ago
#'($turn ENCODED-DIR (string->number DIST)))]
8 years ago
[else #'(void)])
8 years ago
(provide turn)