day 7: initial implementation (it's very spaghet)

This commit is contained in:
xenia 2020-12-07 00:34:21 -05:00
parent 1676b57c8e
commit 3f4c2dea09
1 changed files with 51 additions and 0 deletions

51
7.rkt Normal file
View File

@ -0,0 +1,51 @@
#lang curly-fn racket
(require "scripts/aoc.rkt")
;; solution for day 7
(define (part1 adjlist all-colors wanted)
(define (dfs src dest)
(for/or ([item (in-list (hash-ref adjlist src '()))])
(or (dfs (car item) dest) (string=? (car item) dest))))
;; bad solution
(for/sum ([src (in-set all-colors)])
(if (dfs src wanted) 1 0)))
(define (part2 adjlist all-colors wanted)
(define (part2-impl src)
(add1
(for/sum ([subbag (in-list (hash-ref adjlist src '()))])
(* (cdr subbag) (part2-impl (car subbag))))))
(sub1 (part2-impl wanted)))
(module+ main
(define input (file->lines "inputs/7"))
(define all-colors (mutable-set))
(define adjlist
(for/hash ([line (in-list input)])
(match line
[(pregexp #px"^([a-z ]+) bags contain ([^\\.]+).$" (list _ src-color contains))
(set-add! all-colors src-color)
(values src-color
(if (string=? "no other bags" contains)
'()
(for/list ([item (in-list (string-split contains ", "))])
(match item
[(pregexp #px"^([0-9]+) ([a-z ]+) bag[s]?"
(list _ (app string->number number) color))
(set-add! all-colors color)
(cons color number)]
[x (error "not shonks" x)]))))]
[x (error "not shonks" x)])))
(define wanted "shiny gold")
;; part 1
(answer 7 1 (part1 adjlist all-colors wanted))
;; part 2
(answer 7 2 (part2 adjlist all-colors wanted))
(displayln "meow"))