aoc2022/7.rkt

72 lines
1.8 KiB
Racket
Raw Normal View History

2022-12-07 05:40:25 +00:00
#lang curly-fn racket
(require "scripts/aoc.rkt")
;; solution for day 7
(define (calculate-all-sizes input)
(define file-tree (make-hash))
(define (ft-add-file! ft path name size)
(match path
['() (hash-set! ft name size)]
[(cons fst rst)
(ft-add-file! (hash-ref! ft fst make-hash) rst name size)]))
(for/fold ([cwd '()]) ([inst (in-list input)])
(match inst
[(list 'cd "/") '()]
[(list 'cd "..")
(match cwd
['() '()]
[(cons _ rst) rst])]
[(list 'cd dir) (cons dir cwd)]
[(list 'ls) cwd]
[(list 'dir x) cwd]
[(list 'file file size)
(ft-add-file! file-tree (reverse cwd) file size)
cwd]))
2022-12-07 05:58:19 +00:00
(define sizes '())
2022-12-07 05:40:25 +00:00
2022-12-07 05:58:19 +00:00
(define (record-size! ft)
2022-12-07 05:40:25 +00:00
(define size
2022-12-07 05:58:19 +00:00
(for/sum ([(k v) (in-hash ft)])
2022-12-07 05:40:25 +00:00
(if (number? v)
v
2022-12-07 05:58:19 +00:00
(record-size! v))))
(set! sizes (cons size sizes))
2022-12-07 05:40:25 +00:00
size)
2022-12-07 05:58:19 +00:00
(record-size! file-tree)
(sort sizes <))
2022-12-07 05:40:25 +00:00
(define (part1 input)
(define *at-most* 100000)
(apply + (filter #{< % *at-most*} (calculate-all-sizes input))))
(define (part2 input)
(define *max-used* (- 70000000 30000000))
(define sizes (calculate-all-sizes input))
(define needed-to-free (- (last sizes) *max-used*))
(findf #{>= % needed-to-free} sizes))
(define (parse fname)
(for/list ([line (in-list (file->lines fname))])
(match line
[(pregexp #px"^\\$ cd (.*)$" (list _ dir))
(list 'cd dir)]
[(pregexp #px"^\\$ ls$")
(list 'ls)]
[(pregexp #px"^dir (.*)$" (list _ dir))
(list 'dir dir)]
[(pregexp #px"^([0-9]+) (.*)$" (list _ (app string->number size) file))
(list 'file file size)])))
(module+ main
(define input (parse "inputs/7"))
(answer 7 1 (time (part1 input)))
(answer 7 2 (time (part2 input)))
(displayln "meow"))