aoc2020/8.rkt

55 lines
1.4 KiB
Racket
Raw Normal View History

#lang curly-fn racket
(require "scripts/aoc.rkt")
;; solution for day 8
(struct insn [type arg] #:transparent)
;; helper functions here
2020-12-08 05:26:18 +00:00
(define (execute-program prg)
(define (execute pc acc [seen (mutable-set)])
2020-12-08 05:26:18 +00:00
(cond
[(set-member? seen pc) (cons 'loop acc)]
[(>= pc (vector-length prg)) (cons 'done acc)]
[else
(match-define (insn type arg) (vector-ref prg pc))
(set-add! seen pc)
(match type
["nop" (execute (add1 pc) acc seen)]
["jmp" (execute (+ pc arg) acc seen)]
["acc" (execute (add1 pc) (+ acc arg) seen)])]))
(execute 0 0))
2020-12-08 05:26:18 +00:00
(define (part1 input)
(cdr (execute-program input)))
2020-12-08 05:26:18 +00:00
(define (part2 input)
(let/ec exit
(for ([ins (in-vector input)] [i (in-naturals)]
#:unless (string=? "acc" (insn-type ins)))
(define new-insn
(insn (match (insn-type ins) ["jmp" "nop"] ["nop" "jmp"])
(insn-arg ins)))
(define new-prg (vector-copy input))
(vector-set! new-prg i new-insn)
(match (execute-program new-prg)
[(cons 'loop _) (void)]
[(cons 'done acc) (exit acc)]))))
(module+ main
(define input
2020-12-08 05:26:18 +00:00
(for/vector ([line (in-list (file->lines "inputs/8"))])
(match (string-split line)
[(list a b) (insn a (string->number b))]
[x (error "not shonks" x)])))
2020-12-08 05:26:18 +00:00
;; part 1
(answer 8 1 (part1 input))
;; part 2
(answer 8 2 (part2 input))
(displayln "meow"))