finish day10

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

@ -1,50 +1,44 @@
#lang br/quicklang
(require racket/string (for-syntax syntax/strip-context))
;; http://adventofcode.com/2016/day/10
(provide read-syntax)
(define (read-syntax path port)
(strip-bindings
#`(module mod "lang.rkt"
#,@(for/list ([str (in-lines port)]
#: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
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]))
(define bots (make-hash))
(define outputs (make-hash))
(define chip-comparison-key '(17 61))
(define-macro (value VAL goes to TYPE NUM)
(with-pattern ([HASH-NAME (replace-context #'here (suffix-id #'TYPE "s"))])
#'(begin
(hash-update! HASH-NAME NUM (λ (val) (cons VAL val)) empty)
#;(displayln (format "bots: ~v" bots))
#;(displayln (format "outputs: ~v" outputs)))))
(provide value)
(define gates (make-hash))
(define (bot-low bot)
(define botvals (hash-ref bots bot))
(define minval (car (sort botvals <)))
(hash-set! bots bot (remove minval botvals))
minval)
(define-macro-cases handle
[(_ "value" VAL "goes" "to" TYPE NUM)
#'(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
(handle "value" (gate-low "bot" BOT) "goes" "to" LOW-TYPE LOW-NUM)
(handle "value" (gate-high "bot" BOT) "goes" "to" HIGH-TYPE HIGH-NUM))])
(provide handle)
(define (bot-high bot)
(define botvals (hash-ref bots bot))
(define maxval (car (sort botvals >)))
(hash-set! bots bot (remove maxval botvals))
maxval)
(require sugar/cache)
(define/caching (eval-gate type num)
(for/list ([proc (in-list (hash-ref gates (list type num)))])
(proc)))
; bot BOT gives low to LOW-TYPE LOW-NUM and high to HIGH-TYPE HIGH-NUM
(define-macro (bot BOT gives low to LOW-TYPE LOW-NUM and high to HIGH-TYPE HIGH-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)
(define (gate-low type num) (car (sort (eval-gate type num) <)))
(define (gate-high type num) (car (sort (eval-gate type num) >)))