aboutsummaryrefslogtreecommitdiff
path: root/2021/day3
diff options
context:
space:
mode:
Diffstat (limited to '2021/day3')
-rw-r--r--2021/day3/03a.rkt30
-rw-r--r--2021/day3/03b.rkt35
2 files changed, 65 insertions, 0 deletions
diff --git a/2021/day3/03a.rkt b/2021/day3/03a.rkt
new file mode 100644
index 0000000..bb42d83
--- /dev/null
+++ b/2021/day3/03a.rkt
@@ -0,0 +1,30 @@
+#lang racket
+(define (mode xs)
+ (define ht (make-hash))
+ (define max-key '0)
+ (for ([x xs])
+ (define new-val (+ 1 (hash-ref ht x 0)))
+ (hash-set! ht x new-val)
+ (if (> new-val (hash-ref ht max-key 0)) (set! max-key x) 3))
+ max-key)
+
+(define (transpose xss)
+ (apply map list xss))
+
+(define (flip x)
+ (cond [(string=? x "0") "1"]
+ [else "0"]))
+
+(define input (open-input-file "input"))
+(define bit-positions
+ (transpose (map (lambda (xs)
+ (map (curry make-string 1) (string->list xs)))
+ (port->lines input))))
+
+(define gamma-str (foldr string-append "" (map mode bit-positions)))
+(define epsilon-str (foldr string-append "" (map (compose flip mode) bit-positions)))
+
+(define gamma (string->number gamma-str 2))
+(define epsilon (string->number epsilon-str 2))
+
+(* gamma epsilon)
diff --git a/2021/day3/03b.rkt b/2021/day3/03b.rkt
new file mode 100644
index 0000000..aea9c86
--- /dev/null
+++ b/2021/day3/03b.rkt
@@ -0,0 +1,35 @@
+#lang racket
+
+(define (mode xs)
+ (define ht (make-hash))
+ (define max-key '0)
+ (for ([x xs])
+ (define new-val (+ 1 (hash-ref ht x 0)))
+ (hash-set! ht x new-val)
+ (if (> new-val (hash-ref ht max-key 0)) (set! max-key x) 3))
+ (cond [(= (hash-ref ht #\0 0) (hash-ref ht #\1 0)) #f]
+ [else max-key]))
+
+(define (flip x)
+ (cond [(char=? x #\0) #\1]
+ [else #\0]))
+
+(define (bit-criteria lines least [fallback (cond [least #\0] [else #\1])] [n 0])
+ (cond [(= (length lines) 1) (car lines)]
+ [else
+ (define bits (map (curryr string-ref n) lines))
+ (define bMode (mode bits))
+ (define criteria (cond [(not bMode) fallback]
+ [least (flip bMode)]
+ [else bMode]))
+ (bit-criteria (filter (lambda (x) (char=? criteria (string-ref x n)))
+ lines)
+ least fallback (+ n 1))]))
+
+(define input (open-input-file "input"))
+(define lines (port->lines input))
+
+(define oxy (string->number (bit-criteria lines #f) 2))
+(define co2 (string->number (bit-criteria lines #t) 2))
+
+(* oxy co2)