72 lines
1.8 KiB
Racket
72 lines
1.8 KiB
Racket
#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]))
|
|
|
|
(define sizes '())
|
|
|
|
(define (record-size! ft)
|
|
(define size
|
|
(for/sum ([(k v) (in-hash ft)])
|
|
(if (number? v)
|
|
v
|
|
(record-size! v))))
|
|
(set! sizes (cons size sizes))
|
|
size)
|
|
|
|
(record-size! file-tree)
|
|
(sort sizes <))
|
|
|
|
(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"))
|