Created
May 6, 2018 07:36
-
-
Save cosmez/74f2366e8758db84930270e69290437a to your computer and use it in GitHub Desktop.
Day 8: I Heard You Like Registers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket/base | |
(require (for-syntax syntax/parse racket/base)) | |
(require syntax/strip-context racket/port racket/string) | |
(provide | |
interp | |
read-syntax | |
#%app #%datum #%top #%top-interaction | |
module+ print-results | |
#%module-begin | |
inc dec > < >= <= != == | |
registers) | |
(define (parse-line port) | |
`(interp | |
,@(for/list ([in (in-port read port)]) | |
in))) | |
(define (read-syntax src in) | |
(define lines | |
(for/list ([line (in-lines in)] | |
#:unless (string=? line (string-trim ""))) | |
(parse-line (open-input-string line)))) | |
(define init-module (init)) | |
(strip-context | |
#`(module day08/main "day08.rkt" | |
#,@lines | |
#,init-module))) | |
(define-syntax (interp stx) | |
(syntax-parse stx #:datum-literals(if) | |
[(_ target:id incordec:id incdec-ammnt if source:id comparison:id cmp-ammnt) | |
#`(begin | |
(create 'target) | |
(module+ main | |
(when (comparison (read-register 'source) cmp-ammnt) | |
(incordec 'target incdec-ammnt))))])) | |
(define (init) | |
'(module+ main | |
(print-results))) | |
;;runtime helpers | |
(define registers (make-hash)) | |
(define highest (make-hash)) | |
(define (create register) | |
(when (not (hash-has-key? registers register)) | |
(hash-set! registers register 0) | |
(hash-set! highest register 0))) | |
(define (read-register register) | |
(hash-ref registers register)) | |
(define (read-highest register) | |
(hash-ref highest register)) | |
(define (inc register quantity) | |
(define new-value (+ quantity (read-register register))) | |
(when (> new-value (read-highest register)) | |
(hash-set! highest register new-value )) | |
(hash-set! registers register new-value)) | |
(define (dec register quantity) | |
(define new-value (- (read-register register) quantity)) | |
(when (> new-value (read-highest register)) | |
(hash-set! highest register new-value)) | |
(hash-set! registers register new-value)) | |
(define == equal?) | |
(define (!= v1 v2) (not (equal? v1 v2))) | |
(define (print-results) | |
(displayln (format "~a" registers)) | |
(displayln (format "~a" highest)) | |
(displayln (format "Highest Register: ~a" (car (sort (hash->list registers) > #:key cdr)))) | |
(displayln (format "Highest Ever Register: ~a" (car (sort (hash->list highest) > #:key cdr))))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment