54 lines
1.4 KiB
Racket
54 lines
1.4 KiB
Racket
#lang racket
|
|
|
|
(define range-start 356261)
|
|
(define range-end 846303)
|
|
|
|
;; garbage in garbage out!!!
|
|
(define (nth-digit x n)
|
|
(modulo (floor (/ x (expt 10 n))) 10))
|
|
|
|
(define (has-double? pwd)
|
|
(for/or ([i (in-range 5)])
|
|
(= (nth-digit pwd i)
|
|
(nth-digit pwd (add1 i)))))
|
|
|
|
(define (increasing? pwd)
|
|
(for/and ([i (in-range 5)])
|
|
(>= (nth-digit pwd i)
|
|
(nth-digit pwd (add1 i)))))
|
|
|
|
(define (pwd-valid? pwd)
|
|
(and (has-double? pwd)
|
|
(increasing? pwd)))
|
|
|
|
;; Part 1
|
|
(displayln (for/sum ([i (in-range range-start (add1 range-end))])
|
|
(cond [(pwd-valid? i) 1]
|
|
[else 0])))
|
|
|
|
;; okay we're going to do this the spaghetti way
|
|
(define (has-exact-double? pwd)
|
|
(for/or ([i (in-range 5)])
|
|
(and
|
|
;; ith digit is the same is (i+1)th digit
|
|
(= (nth-digit pwd i)
|
|
(nth-digit pwd (add1 i)))
|
|
;; ith digit is not the same as (i+2)th digit, if exists
|
|
(not (= (nth-digit pwd i)
|
|
(cond
|
|
[(> i 3) -1]
|
|
[else (nth-digit pwd (+ i 2))])))
|
|
;; ith digit is also not the same as (i-1)th digit, if exists
|
|
(not (= (nth-digit pwd i)
|
|
(cond
|
|
[(zero? i) -1]
|
|
[else (nth-digit pwd (sub1 i))]))))))
|
|
|
|
(define (pwd-valid2? pwd)
|
|
(and (has-exact-double? pwd)
|
|
(increasing? pwd)))
|
|
|
|
;; Part 2
|
|
(displayln (for/sum ([i (in-range range-start (add1 range-end))])
|
|
(cond [(pwd-valid2? i) 1]
|
|
[else 0]))) |