day 8: ok this one is actually better

This commit is contained in:
xenia 2020-12-08 00:26:18 -05:00
parent 1daa7758cc
commit f032b43a80
1 changed files with 27 additions and 39 deletions

66
8.rkt
View File

@ -8,55 +8,43 @@
;; helper functions here ;; helper functions here
(define (part1 input) (define (execute-program prg)
(define (execute pc acc [seen (mutable-set)]) (define (execute pc acc [seen (mutable-set)])
(if (set-member? seen pc) (cond
acc [(set-member? seen pc) (cons 'loop acc)]
(let ([in (list-ref input pc)]) [(>= pc (vector-length prg)) (cons 'done acc)]
(set-add! seen pc) [else
(match (insn-type in) (match-define (insn type arg) (vector-ref prg pc))
["nop" (execute (add1 pc) acc seen)] (set-add! seen pc)
["jmp" (execute (+ pc (insn-arg in)) acc seen)] (match type
["acc" (execute (add1 pc) (+ acc (insn-arg in)) seen)] ["nop" (execute (add1 pc) acc seen)]
[x (error "not shonks" x)])))) ["jmp" (execute (+ pc arg) acc seen)]
["acc" (execute (add1 pc) (+ acc arg) seen)])]))
(execute 0 0)) (execute 0 0))
(define (part1 input)
(cdr (execute-program input)))
(define (part2 input) (define (part2 input)
(define (execute-actual input) (let/ec exit
(define (execute pc acc [seen (mutable-set)]) (for ([ins (in-vector input)] [i (in-naturals)]
(if (>= pc (length input)) #:unless (string=? "acc" (insn-type ins)))
acc (define new-insn
(let ([in (list-ref input pc)]) (insn (match (insn-type ins) ["jmp" "nop"] ["nop" "jmp"])
(set-add! seen pc) (insn-arg ins)))
(match (insn-type in) (define new-prg (vector-copy input))
["nop" (execute (add1 pc) acc seen)] (vector-set! new-prg i new-insn)
["jmp" (execute (+ pc (insn-arg in)) acc seen)] (match (execute-program new-prg)
["acc" (execute (add1 pc) (+ acc (insn-arg in)) seen)] [(cons 'loop _) (void)]
[x (error "not shonks" x)])))) [(cons 'done acc) (exit acc)]))))
(execute 0 0))
(define target-pc (length input))
(for ([in (in-list input)] [i (in-naturals)] #:unless (string=? "acc" (insn-type in)))
(define new-type (if (string=? (insn-type in) "jmp") "nop" "jmp"))
(define new-insn (insn new-type (insn-arg in)))
;; aaaa
(define vec (vector-copy (list->vector input)))
(vector-set! vec i new-insn)
(define new-prg (vector->list vec))
(with-handlers ([exn? (lambda (x) (answer 8 2 (execute-actual new-prg)))])
(part1 new-prg))))
(module+ test
(require rackunit)
;; tests here
(displayln "no tests :("))
(module+ main (module+ main
(define input (define input
(for/list ([line (in-list (file->lines "inputs/8"))]) (for/vector ([line (in-list (file->lines "inputs/8"))])
(match (string-split line) (match (string-split line)
[(list a b) (insn a (string->number b))] [(list a b) (insn a (string->number b))]
[x (error "not shonks" x)]))) [x (error "not shonks" x)])))
;; part 1 ;; part 1
(answer 8 1 (part1 input)) (answer 8 1 (part1 input))