simplify loop

master
Matthew Butterick 5 years ago
parent 059196c48f
commit 140d537c4b

@ -1,5 +1,5 @@
#lang br #lang br
(require racket/file rackunit racket/set) (require racket/file rackunit racket/set racket/dict)
(define (line->wire ln) (define (line->wire ln)
;; convert string to a wire ;; convert string to a wire
@ -10,21 +10,17 @@
(define (wire->locs wire) (define (wire->locs wire)
;; list of every grid location visited by a wire ;; list of every grid location visited by a wire
(for/fold ([locs (list 0)] ;; use complex numbers to model x, y locations
#:result (reverse locs)) (for*/fold ([locs (list 0)]
([move (in-list wire)]) #:result (reverse locs))
(append ([(dir dist) (in-dict wire)]
(match move [complex-unit (in-value (match dir
[(cons dir dist) ['L -1]
(define origin (car locs)) ['R 1]
(for/fold ([locs null]) ['U +i]
([i (in-range dist)]) ['D -i]))]
(define next-loc (+ origin (* (match dir [i (in-range dist)])
['L -1] (cons (+ (car locs) complex-unit) locs)))
['R 1]
['U +i]
['D -i]) (add1 i))))
(cons next-loc locs))]) locs)))
(define test-w1 (line->wire "R8,U5,L5,D3")) (define test-w1 (line->wire "R8,U5,L5,D3"))
(check-equal? (check-equal?