1
0
Fork 0

Day 03: Use for/fold instead of loop.

This commit is contained in:
Jonathan Chan 2021-12-02 22:25:41 -08:00 committed by Jonathan Chan
parent 2fd90a23d1
commit c0a6ec178b
2 changed files with 14 additions and 10 deletions

View File

@ -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)))

View File

@ -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 <)))