Day 03: Use for/fold instead of loop.
This commit is contained in:
parent
56ae75908b
commit
1ed23c13fd
5
lib.rkt
5
lib.rkt
|
@ -73,6 +73,11 @@
|
|||
(define (string->binary str)
|
||||
(string->number (string-append "#b" str)))
|
||||
|
||||
;; chars->binary : (listof char?) -> number?
|
||||
;; Given a list of characters representing the bits of a binary number,
|
||||
;; convert it into the number it represents
|
||||
(define chars->binary (∘ string->binary list->string))
|
||||
|
||||
;; string->vector : string? -> (vectorof char?)
|
||||
(define (string->vector str)
|
||||
(list->vector (string->list str)))
|
||||
|
|
19
src/03.rkt
19
src/03.rkt
|
@ -6,26 +6,25 @@
|
|||
(for/list ([b (problem-input 3)])
|
||||
(string->list b)))
|
||||
|
||||
(define chars->binary
|
||||
(∘ string->binary list->string))
|
||||
(define bits (length (first input)))
|
||||
|
||||
(define (nth-bit nums p n)
|
||||
(let ([bs (map #{list-ref % n} nums)])
|
||||
(if (p (count (∂ char=? #\1) bs) (/ (length nums) 2))
|
||||
(if (p (count #{char=? % #\1} bs) (/ (length nums) 2))
|
||||
#\1 #\0)))
|
||||
|
||||
(define (squimsh p)
|
||||
(~> (range (length (first input)))
|
||||
(~> (range bits)
|
||||
(map #{nth-bit input p %} _)
|
||||
chars->binary))
|
||||
|
||||
(define (search p)
|
||||
(let loop ([nums input]
|
||||
[n 0])
|
||||
(if (= (length nums) 1)
|
||||
(chars->binary (first nums))
|
||||
(let ([bit (nth-bit nums p n)])
|
||||
(loop (filter #{char=? bit (list-ref % n)} nums) (add1 n))))))
|
||||
(for/fold ([nums input]
|
||||
#:result (chars->binary (first nums)))
|
||||
([n (range bits)]
|
||||
#:break (singleton? nums))
|
||||
(define bit (nth-bit nums p n))
|
||||
(filter #{char=? bit (list-ref % n)} nums)))
|
||||
|
||||
(define part1
|
||||
(* (squimsh >=) (squimsh <)))
|
||||
|
|
Loading…
Reference in New Issue