finish day10

2016
Matthew Butterick 8 years ago
parent 5d101ecfbe
commit 05f1f914db

@ -1,50 +1,44 @@
#lang br/quicklang #lang br/quicklang
(require racket/string (for-syntax syntax/strip-context))
;; http://adventofcode.com/2016/day/10 ;; http://adventofcode.com/2016/day/10
(provide read-syntax) (provide read-syntax)
(define (read-syntax path port) (define (read-syntax path port)
(strip-bindings (strip-bindings
#`(module mod "lang.rkt" #`(module mod "lang.rkt"
#,@(for/list ([str (in-lines port)] #,@(for/list ([str (in-lines port)]
#:when (not (equal? str ""))) #:when (not (equal? str "")))
(format-datum '~a str))))) `(handle ,@(string-split str))))))
(define-macro (mb ARG ...) (define chip-comparison-key '(17 61))
(define-macro (mb . ARGS)
#'(#%module-begin #'(#%module-begin
ARG ... (begin . ARGS)
)) (displayln
(for/first ([(k v) (in-hash gates)]
#:when (equal? (sort (apply eval-gate k) <)
(sort chip-comparison-key <)))
k))
(displayln (for/product ([i (in-range 3)])
(gate-low "output" (~a i))))))
(provide (rename-out [mb #%module-begin])) (provide (rename-out [mb #%module-begin]))
(define bots (make-hash)) (define gates (make-hash))
(define outputs (make-hash))
(define chip-comparison-key '(17 61)) (define-macro-cases handle
(define-macro (value VAL goes to TYPE NUM) [(_ "value" VAL "goes" "to" TYPE NUM)
(with-pattern ([HASH-NAME (replace-context #'here (suffix-id #'TYPE "s"))]) #'(hash-update! gates (list TYPE NUM) (λ (val) (cons (λ () (let ([v VAL])
(if (string? v)
(string->number v)
v))) val)) empty)]
[(_ "bot" BOT "gives" "low" "to" LOW-TYPE LOW-NUM "and" "high" "to" HIGH-TYPE HIGH-NUM)
#'(begin #'(begin
(hash-update! HASH-NAME NUM (λ (val) (cons VAL val)) empty) (handle "value" (gate-low "bot" BOT) "goes" "to" LOW-TYPE LOW-NUM)
#;(displayln (format "bots: ~v" bots)) (handle "value" (gate-high "bot" BOT) "goes" "to" HIGH-TYPE HIGH-NUM))])
#;(displayln (format "outputs: ~v" outputs))))) (provide handle)
(provide value)
(define (bot-low bot)
(define botvals (hash-ref bots bot))
(define minval (car (sort botvals <)))
(hash-set! bots bot (remove minval botvals))
minval)
(define (bot-high bot) (require sugar/cache)
(define botvals (hash-ref bots bot)) (define/caching (eval-gate type num)
(define maxval (car (sort botvals >))) (for/list ([proc (in-list (hash-ref gates (list type num)))])
(hash-set! bots bot (remove maxval botvals)) (proc)))
maxval)
; bot BOT gives low to LOW-TYPE LOW-NUM and high to HIGH-TYPE HIGH-NUM (define (gate-low type num) (car (sort (eval-gate type num) <)))
(define-macro (bot BOT gives low to LOW-TYPE LOW-NUM and high to HIGH-TYPE HIGH-NUM) (define (gate-high type num) (car (sort (eval-gate type num) >)))
#'(module+ main
(when (equal? (sort (hash-ref bots BOT) <) (sort chip-comparison-key <))
(displayln (format "answer: bot ~a holds ~a chips" BOT chip-comparison-key)))
(value (bot-low BOT) goes to LOW-TYPE LOW-NUM)
(value (bot-high BOT) goes to HIGH-TYPE HIGH-NUM)))
(provide bot and)