Skip to content

Instantly share code, notes, and snippets.

@angus-g
Created December 5, 2019 07:05
Show Gist options
  • Select an option

  • Save angus-g/f84fc048a9af391f2f91d0470243a7fc to your computer and use it in GitHub Desktop.

Select an option

Save angus-g/f84fc048a9af391f2f91d0470243a7fc to your computer and use it in GitHub Desktop.
advent of code day 5
#lang racket
(require racket/vector)
(define in (file->string "day5.in"))
(define initial-memory (list->vector (map string->number (string-split in ","))))
(define mem (vector-copy initial-memory))
; indirect addressing (with optional offset)
(define (ind pos [off 0])
(vector-ref mem (addr pos off)))
; access memory at position (with optional offset)
(define (addr pos [off 0])
(vector-ref mem (+ pos off)))
(define (step ip inputs)
(let* ([insn (addr ip)]
[imm1 (>= (remainder insn 1000) 100)]
[ref1 (if imm1 addr ind)]
[imm2 (>= (remainder insn 10000) 1000)]
[ref2 (if imm2 addr ind)]
[insn (remainder insn 100)])
(case insn
[(1) ; add
(vector-set! mem (addr ip 3)
(+ (ref1 ip 1) (ref2 ip 2)))
(step (+ ip 4) inputs)]
[(2) ; multiply
(vector-set! mem (addr ip 3)
(* (ref1 ip 1) (ref2 ip 2)))
(step (+ ip 4) inputs)]
[(3) ; input
(vector-set! mem (addr ip 1) (first inputs))
(step (+ ip 2) (rest inputs))]
[(4) ; output
(displayln (ref1 ip 1))
(step (+ ip 2) inputs)]
[(5) ; jump if true
(let ([next (if (not (zero? (ref1 ip 1)))
(ref2 ip 2)
(+ ip 3))])
(step next inputs))]
[(6) ; jump if false
(let ([next (if (zero? (ref1 ip 1))
(ref2 ip 2)
(+ ip 3))])
(step next inputs))]
[(7) ; less
(vector-set! mem (addr ip 3)
(if (< (ref1 ip 1) (ref2 ip 2)) 1 0))
(step (+ ip 4) inputs)]
[(8) ; equal
(vector-set! mem (addr ip 3)
(if (= (ref1 ip 1) (ref2 ip 2)) 1 0))
(step (+ ip 4) inputs)]
[(99) ; successful halt
#t])))
(define (run inputs)
(vector-copy! mem 0 initial-memory)
(step 0 inputs))
; part 1
(run '(1))
; part 2
(run '(5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment