Created
December 8, 2019 16:29
-
-
Save sotolf2/cd71fe3c773bb7d29e07a6c06c4e0a49 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
(require threading) | |
(define test-img '(((0 2) | |
(2 2)) | |
((1 1) | |
(2 2)) | |
((2 2) | |
(1 2)) | |
((0 0) | |
(0 0)))) | |
(define (get-input) | |
(car (file->lines "day8.txt"))) | |
(define (split-every num lst) | |
(define (step inlist num res) | |
(if (empty? inlist) | |
(reverse res) | |
(step (drop inlist num) | |
num | |
(cons (take inlist num) res)))) | |
(step lst num '())) | |
(define (text->img txt) | |
(~>> (string->list (get-input)) | |
(map char->integer) | |
(map (λ (ascii) (- ascii 48))) | |
(split-every 25) | |
(split-every 6))) | |
(define (count-layer lst) | |
(define (count-chars lst hsh) | |
(if (empty? lst) | |
hsh | |
(count-chars (cdr lst) (hash-update hsh (car lst) (λ (n) (+ n 1)) 0)))) | |
(define (count-list lst hsh) | |
(if (empty? lst) | |
hsh | |
(count-list (cdr lst) (count-chars (car lst) hsh)))) | |
(count-list lst #hash())) | |
(define (fewest-zeros a b) | |
(if (< (hash-ref a 0 0) (hash-ref b 0 0)) | |
a b)) | |
(define (part1) | |
(let* ([counts (~>> (text->img (get-input)) (map count-layer))] | |
[goal (foldl fewest-zeros (car counts) (cdr counts))]) | |
(* (hash-ref goal 1) (hash-ref goal 2)))) | |
(define (compact-layers layers) | |
(define (compact-chars chars res) | |
(car (filter-not (λ (n) (= 2 n)) chars))) | |
(define (compact-rows rows res) | |
(if (empty? (car rows)) | |
(reverse res) | |
(compact-rows (map cdr rows) (cons (compact-chars (map car rows) '()) res)))) | |
(define (compact layers res) | |
(if (empty? (car layers)) | |
(reverse res) | |
(compact (map cdr layers) (cons (compact-rows (map car layers) '()) res)))) | |
(compact layers '())) | |
(define (draw img) | |
(define (digit->char n) | |
(if (= 1 n) | |
#\# | |
#\ )) | |
(define (line->str line) | |
(list->string(map digit->char line))) | |
(string-join (map line->str img) "\n")) | |
(define (part2) | |
(display (draw (compact-layers (text->img (get-input)))))) | |
(part1) | |
(part2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment