finish day05 (very slow)

2016
Matthew Butterick 8 years ago
parent 87d3d263d7
commit 5f292272d4

@ -4,22 +4,38 @@
(define (read-syntax path port) (define (read-syntax path port)
(strip-bindings (strip-bindings
#`(module mod "day05.rkt" #`(module mod "day05.rkt"
(solve-part-a #,(string-trim (port->string port)))))) (solve #,(string-trim (port->string port))))))
(module+ reader (provide read-syntax)) (module+ reader (provide read-syntax))
(provide #%module-begin) (provide #%module-begin)
(define (solve-part-a key) (define (solve key)
(display "part a solution: ") (define-values
(for*/fold ([password-cs empty]) (part-a-solution part-b-solution)
([idx (in-naturals)] (for*/fold ([part-a empty]
[part-b (make-vector 8 #f)])
([idx (in-naturals 1000000)]
[this-key (in-value (format "~a~a" key idx))] [this-key (in-value (format "~a~a" key idx))]
#:break (= 8 (length password-cs))) #:break (and (= 8 (length part-a))
(andmap string? (vector->list part-b))))
(define this-hash (md5 (open-input-string this-key))) (define this-hash (md5 (open-input-string this-key)))
(if (string-prefix? this-hash "00000") (define next-part-a
(if (and (not (= 8 (length part-a)))
(string-prefix? this-hash "00000"))
(let ([next-str (substring this-hash 5 6)]) (let ([next-str (substring this-hash 5 6)])
(display next-str) (displayln (format "part a progress: ~a" next-str))
(cons next-str password-cs)) (cons next-str part-a))
password-cs)) part-a))
(displayln "")) (define next-part-b
(provide solve-part-a) (let ()
(when (and (string-prefix? this-hash "00000")
(string->number (substring this-hash 5 6))
(<= 0 (string->number (substring this-hash 5 6)) 7)
(not (vector-ref part-b (string->number (substring this-hash 5 6)))))
(displayln (format "part b progress: idx ~a, hash ~a, ~a at ~a" idx this-hash (substring this-hash 6 7) (substring this-hash 5 6)))
(vector-set! part-b (string->number (substring this-hash 5 6)) (substring this-hash 6 7)))
part-b))
(values next-part-a next-part-b)))
(displayln (format "part a: ~a" (apply string-append (reverse part-a-solution))))
(displayln (format "part b: ~a" (apply string-append (vector->list part-b-solution)))))
(provide solve)