use integers

master
Matthew Butterick 5 years ago
parent 6d15732673
commit 43bd2577f8

@ -4,45 +4,40 @@
(match-define (list low high) (match-define (list low high)
(map string->number (string-split (file->string "04.rktd") "-"))) (map string->number (string-split (file->string "04.rktd") "-")))
(define (double-digit? num) (define (find-doubles digits)
(define numstr (number->string num)) (match (for/list ([d0 (in-list digits)]
(match (for/list ([c0 (in-string numstr)] [d1 (in-list (cdr digits))]
[c1 (in-string numstr 1)] #:when (= d0 d1))
#:when (char=? c0 c1)) d0)
(string->number (string c0)))
[(? null?) #false] [(? null?) #false]
[nums nums])) [dds (remove-duplicates dds)]))
(define (num->digits num) (define (num->digits num)
(for/list ([c (in-string (number->string num))]) (for/list ([c (in-string (number->string num))])
(string->number (string c)))) (string->number (string c))))
(define (monotonic? num) (define (increasing? digits) (apply <= digits))
(apply <= (num->digits num)))
;; 1 ;; 1
(check-eq? (check-eq?
(for/sum ([num (in-range low (add1 high))] (for/sum ([digits (in-list (map num->digits (range low (add1 high))))])
#:when (and (double-digit? num) (monotonic? num))) (match digits
1) [(and (? find-doubles) (? increasing?)) 1]
[_ 0]))
1079) 1079)
(define (triple-digit? num digit) (define (triple-digit? ds d)
(define numstr (number->string num)) (and (pair? ds)
(define digitc (car (string->list (number->string digit)))) (or (list-prefix? (list d d d) ds)
(for/or ([c0 (in-string numstr)] (triple-digit? (cdr ds) d))))
[c1 (in-string numstr 1)]
[c2 (in-string numstr 2)])
(char=? c0 c1 c2 digitc)))
;;2 ;; 2
(check-eq? (check-eq?
(for/sum ([num (in-range low (add1 high))] (for/sum ([digits (in-list (map num->digits (range low (add1 high))))])
#:when (and (for/or ([digits (in-value (double-digit? num))] (match digits
#:when digits [(and (app find-doubles (? list? doubled-digits)) (? increasing?))
[digit (in-list digits)]) #:when (for/or ([dd (in-list doubled-digits)])
(not (triple-digit? num digit))) (not (triple-digit? digits dd))) 1]
(monotonic? num))) [_ 0]))
1)
699) 699)