aoc2020/8.rkt

55 lines
1.4 KiB
Racket

#lang curly-fn racket
(require "scripts/aoc.rkt")
;; solution for day 8
(struct insn [type arg] #:transparent)
;; helper functions here
(define (execute-program prg)
(define (execute pc acc [seen (mutable-set)])
(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))
(define (part1 input)
(cdr (execute-program input)))
(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
(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)])))
;; part 1
(answer 8 1 (part1 input))
;; part 2
(answer 8 2 (part2 input))
(displayln "meow"))