From f032b43a80e6884618a5bdfb33ee3668ed563986 Mon Sep 17 00:00:00 2001 From: haskal Date: Tue, 8 Dec 2020 00:26:18 -0500 Subject: [PATCH] day 8: ok this one is actually better --- 8.rkt | 66 ++++++++++++++++++++++++----------------------------------- 1 file changed, 27 insertions(+), 39 deletions(-) diff --git a/8.rkt b/8.rkt index e320ee8..93e4cec 100644 --- a/8.rkt +++ b/8.rkt @@ -8,55 +8,43 @@ ;; helper functions here -(define (part1 input) +(define (execute-program prg) (define (execute pc acc [seen (mutable-set)]) - (if (set-member? seen pc) - acc - (let ([in (list-ref input pc)]) - (set-add! seen pc) - (match (insn-type in) - ["nop" (execute (add1 pc) acc seen)] - ["jmp" (execute (+ pc (insn-arg in)) acc seen)] - ["acc" (execute (add1 pc) (+ acc (insn-arg in)) seen)] - [x (error "not shonks" x)])))) + (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) - (define (execute-actual input) - (define (execute pc acc [seen (mutable-set)]) - (if (>= pc (length input)) - acc - (let ([in (list-ref input pc)]) - (set-add! seen pc) - (match (insn-type in) - ["nop" (execute (add1 pc) acc seen)] - ["jmp" (execute (+ pc (insn-arg in)) acc seen)] - ["acc" (execute (add1 pc) (+ acc (insn-arg in)) seen)] - [x (error "not shonks" x)])))) - (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 :(")) + (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/list ([line (in-list (file->lines "inputs/8"))]) + (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))