badkins
2021-12-4 01:18:05

One of the things I really enjoy about Advent of Code is taking other solutions and porting them to Racket, because Racket usually makes this trivial regardless of the language. Someone in our local Triangle NC slack came up with <https://github.com/tginsberg/advent–2021-kotlin/blob/master/src/main/kotlin/com/ginsberg/advent2021/Day03.kt|a nice Kotlin version> , so I tried to port it as closely as possible (hence over using threading macros :) ). I’m pretty pleased with how closely I was able to match it with <https://github.com/lojic/LearningRacket/blob/master/advent-of-code–2021/solutions/day03/day03-toddginsberg.rkt|this Racket version> (spoilers obviously, but it’s pretty late).


ben.knoble
2021-12-4 03:37:52

For the record, here’s what raco fmt gives; a lot easier to read: #lang racket ;; Version inspired by Todd Ginsberg's version (require threading) (define input (file-&gt;lines "day03.txt")) (define (solve-part1 input) (let* ([gamma (~&gt;&gt; input first indices (map (λ (column) (if (&gt; (count (λ (it) (char=? (chr it column) #\1)) input) (/ (length input) 2)) #\1 #\0))) list-&gt;string)] [epsilon (~&gt;&gt; gamma string-&gt;list (map (λ (it) (if (char=? it #\1) #\0 #\1))) list-&gt;string)]) (* (~&gt; gamma to-int) (~&gt; epsilon to-int)))) (define (solve-part2 input) (* (~&gt; input (bitwise-filter #t) to-int) (~&gt; input (bitwise-filter #f) to-int))) (define (bitwise-filter input keep-most-common) (~&gt;&gt; input first indices (foldl (λ (column inputs) (if (= (length inputs) 1) inputs (let-values ([(lst1 lst2) (~&gt;&gt; inputs (partition (λ (it) (char=? (chr it column) #\1))))]) (choose (if keep-most-common &gt;= &lt;) lst1 lst2)))) input) first)) (define (choose pred? lst1 lst2) (if (pred? (length lst1) (length lst2)) lst1 lst2)) ;; -------------------------------------------------------------------------------------------- ;; Support code ;; -------------------------------------------------------------------------------------------- (define (indices s) (range (string-length s))) (define (to-int s) (read (open-input-string (format "#b~a" s)))) (define (chr s pos) (string-ref s pos)) (module+ test (require rackunit) (check-equal? (solve-part1 input) 852500) (check-equal? (solve-part2 input) 1007985))


massung
2021-12-4 06:50:58

Day 4 the puzzles start getting a bit more interesting… :wink:



popa.bogdanp
2021-12-4 07:11:34

Nice! Our solutions are pretty similar: https://github.com/Bogdanp/aoc2021/blob/master/day04.rkt

We both have a struct w/ an index from nums to positions, but using a bitmap for the checks is definitely nicer than my matrix.