This commit is contained in:
xenia 2022-12-07 00:40:25 -05:00
parent e1b43ac9fb
commit a58b1b478f
3 changed files with 1145 additions and 0 deletions

77
7.rkt Normal file
View File

@ -0,0 +1,77 @@
#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 (make-hash))
(define (ft-lookup ft path)
(match path
['() ft]
[(cons fst rst) (ft-lookup (hash-ref ft fst) rst)]))
(define (record-size! ft path)
(define size
(for/sum ([(k v) (in-hash (ft-lookup ft path))])
(if (number? v)
v
(record-size! ft (append path (list k))))))
(hash-set! sizes path size)
size)
(record-size! file-tree '())
(sort (hash-values 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"))

1045
inputs/7 Normal file

File diff suppressed because it is too large Load Diff

23
inputs/7-test1 Normal file
View File

@ -0,0 +1,23 @@
$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k