aoc2022/5.rkt

61 lines
2.1 KiB
Racket

#lang curly-fn racket
(require "scripts/aoc.rkt")
;; solution for day 5
(define (part1 input)
(match-define (list stacks moves) input)
(define end-stacks
(for/fold ([stacks stacks]) ([move (in-list moves)])
(match-define (list ct (app sub1 from) (app sub1 to)) move)
(define movement (take (list-ref stacks from) ct))
(for/list ([stack (in-list stacks)] [i (in-naturals)])
(match i
[(== from) (drop stack ct)]
[(== to) (append (reverse movement) stack)]
[else stack]))))
(apply string-append (map first end-stacks)))
(define (part2 input)
(match-define (list stacks moves) input)
(define end-stacks
(for/fold ([stacks stacks]) ([move (in-list moves)])
(match-define (list ct (app sub1 from) (app sub1 to)) move)
(define movement (take (list-ref stacks from) ct))
(for/list ([stack (in-list stacks)] [i (in-naturals)])
(match i
[(== from) (drop stack ct)]
[(== to) (append movement stack)]
[else stack]))))
(apply string-append (map first end-stacks)))
(define (parse fname)
(match-define (list stacks moves) (string-split (file->string fname) "\n\n"))
(define stack-lines (string-split stacks "\n"))
(define columns
(for/list ([x (in-list (string->list (last stack-lines)))]
[i (in-naturals)]
#:unless (equal? x #\space))
i))
(define stacks-data
(for/list ([col (in-list columns)])
(reverse
(for*/list ([line (in-list (rest (reverse stack-lines)))]
[letter (in-value (substring line col (add1 col)))]
#:unless (equal? " " letter))
letter))))
(define moves-data
(for/list ([line (in-list (string-split moves "\n"))])
(define parts (string-split line " "))
(list (string->number (second parts))
(string->number (fourth parts))
(string->number (sixth parts)))))
(list stacks-data moves-data))
(module+ main
(define input (parse "inputs/5"))
(answer 5 1 (time (part1 input)))
(answer 5 2 (time (part2 input)))
(displayln "meow"))