diff options
author | Leah Neukirchen <leah@vuxu.org> | 2022-12-06 19:46:18 +0100 |
---|---|---|
committer | Leah Neukirchen <leah@vuxu.org> | 2022-12-06 19:46:18 +0100 |
commit | b8dca4302904f7356fd2b0c462e6965824ba582a (patch) | |
tree | d2e990d5ef60fd195a18365543e3b3f379caa62e | |
parent | 0ffe55a0d6d5dbcff5cbc19507b336366f7fb40c (diff) | |
download | adventofcode2022-b8dca4302904f7356fd2b0c462e6965824ba582a.tar.gz adventofcode2022-b8dca4302904f7356fd2b0c462e6965824ba582a.tar.xz adventofcode2022-b8dca4302904f7356fd2b0c462e6965824ba582a.zip |
day05: make nicer
-rw-r--r-- | day05.rkt | 51 |
1 files changed, 28 insertions, 23 deletions
diff --git a/day05.rkt b/day05.rkt index 76d6350..e981862 100644 --- a/day05.rkt +++ b/day05.rkt @@ -1,29 +1,34 @@ #lang racket -(let-values ([(stacks steps) (splitf-at (file->lines "day05") - (lambda (s) (not (equal? s ""))))]) +(define-values (stacks raw-steps) + (let ((lines (file->lines "day05"))) + (split-at lines (index-of lines "")))) - (let* ([state (for/vector ([x (in-range 1 35 4)]) - (dropf (for/list ([y (in-range 0 (sub1 (length stacks)))]) - (string-ref (list-ref stacks y) x)) - (lambda (c) (equal? c #\space))))] - [steps (for/list ([line (cdr steps)]) - (remove* '(#f) (map string->number (string-split line " "))))] - [solve (lambda (state f) - (for ([step steps]) - (let* ([n (first step)] - [from (sub1 (second step))] - [to (sub1 (third step))] +(define initial-state + (for/vector ([x (in-range 1 35 4)]) + (dropf (for/list ([stack (drop-right stacks 1)]) + (string-ref stack x)) + (curry equal? #\space)))) - [taken (take (vector-ref state from) n)] - [left (drop (vector-ref state from) n)] - [placed (append (f taken) (vector-ref state to))]) - (vector-set! state to placed) - (vector-set! state from left))) - (list->string (for/list ([s state]) - (first s))))]) - (displayln (solve (vector-copy state) reverse)) - (displayln (solve (vector-copy state) identity)) - )) +(define steps + (for/list ([line (cdr raw-steps)]) + (filter number? (map string->number (string-split line " "))))) + +(define (solve f) + (define state (vector-copy initial-state)) + (for ([step steps]) + (let* ([n (first step)] + [from (sub1 (second step))] + [to (sub1 (third step))] + + [taken (take (vector-ref state from) n)] + [left (drop (vector-ref state from) n)] + [placed (append (f taken) (vector-ref state to))]) + (vector-set! state to placed) + (vector-set! state from left))) + (list->string (for/list ([s state]) (first s)))) + +(solve reverse) +(solve identity) ; MQTPGLLDN ; LVZPSTTCZ |