Day 03: Use for/fold instead of loop.

This commit is contained in:
Jonathan Chan 2021-12-02 22:25:41 -08:00
parent 56ae75908b
commit 1ed23c13fd
2 changed files with 14 additions and 10 deletions

View File

@ -73,6 +73,11 @@
(define (string->binary str) (define (string->binary str)
(string->number (string-append "#b" 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?) ;; string->vector : string? -> (vectorof char?)
(define (string->vector str) (define (string->vector str)
(list->vector (string->list str))) (list->vector (string->list str)))

View File

@ -6,26 +6,25 @@
(for/list ([b (problem-input 3)]) (for/list ([b (problem-input 3)])
(string->list b))) (string->list b)))
(define chars->binary (define bits (length (first input)))
( string->binary list->string))
(define (nth-bit nums p n) (define (nth-bit nums p n)
(let ([bs (map #{list-ref % n} nums)]) (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))) #\1 #\0)))
(define (squimsh p) (define (squimsh p)
(~> (range (length (first input))) (~> (range bits)
(map #{nth-bit input p %} _) (map #{nth-bit input p %} _)
chars->binary)) chars->binary))
(define (search p) (define (search p)
(let loop ([nums input] (for/fold ([nums input]
[n 0]) #:result (chars->binary (first nums)))
(if (= (length nums) 1) ([n (range bits)]
(chars->binary (first nums)) #:break (singleton? nums))
(let ([bit (nth-bit nums p n)]) (define bit (nth-bit nums p n))
(loop (filter #{char=? bit (list-ref % n)} nums) (add1 n)))))) (filter #{char=? bit (list-ref % n)} nums)))
(define part1 (define part1
(* (squimsh >=) (squimsh <))) (* (squimsh >=) (squimsh <)))