AoC'21, day 3, first problem rvc


Each bit of one number is the majority bit in a column, each bit of the other number is the minority bit.

 $ cat 03a.rkt 
 #lang racket 
  
  
 (provide 
   example-data 
   read-input) 
  
  
 (require 
   (prefix-in aoc: "aoc.rkt") 
   (prefix-in srfi1: srfi/1) 
   (prefix-in utl: "../scheme/utl.rkt")) 
  
  
 (define (aoc03a . input) 
  
   ; Return the power consumption from the given diagnostic 
   ; report.  If no report is given, use the contest problem 
   ; input; otherwise assume the argument is the string 
   ; representation of a problem input. 
  
   (power-consumption (apply read-input input))) 
  
  
 (define  (read-input . input) 
  
   ; Return the given diagnostic report.  If no report is given, 
   ; use the contest problem input; otherwise assume the argument 
   ; is the string representation of a problem input. 
  
   (map 
     aoc:digit-string->digit-list 
     (flatten 
       (car (aoc:aoc-read-input (if (null? input) 3 (car input))))))) 
  
  
 (define (power-consumption readings) 
  
   ; Return the power consumption indicated by the given readings. 
    
  
   (define (epsilon-gamma ones-counts bit-count) 
  
     ; Return (e . g) where e is the epsilon value based on the 
     ; given ones counts and g is the gamma value. 
  
     (let 
  
       ((majority-count (ceiling (/ bit-count 2)))) 
        
       (foldl 
  
         (lambda (oc eg) 
           (let ((e (* (car eg) 2)) 
                 (g (* (cdr eg) 2))) 
             (if (< oc majority-count) 
                 (cons (+ e 1) g) 
                 (cons e (+ g 1))))) 
  
         (cons 0 0) 
  
         ones-counts))) 
  
  
   (define (ones-counts readings) 
  
     ; Return a list of one-bit counts, where the ith element in 
     ; the returned list (i = 0 is leftmost) is the count of bit 
     ; lists in the given list of bit lists that have a one bit as 
     ; their ith element.  The given list is assumed non-empty. 
      
  
     (define (add-rows r1 r2) 
  
       ; Return the element-by-element sum of the given lists. 
  
       (map (lambda (s) (apply + s)) (srfi1:zip r1 r2))) 
  
      
     (foldl 
       (lambda (n s) (add-rows n s)) 
       (car readings) 
       (cdr readings))) 
  
  
   (let* 
  
     ((oc (ones-counts readings)) 
      (eg (epsilon-gamma oc (length readings)))) 
  
     (* (car eg) (cdr eg)))) 
  
  
 (module+ main 
  
   (aoc03a)) 
  
  
 (aoc:define-string example-data 
   "00100" 
   "11110" 
   "10110" 
   "10111" 
   "10101" 
   "01111" 
   "00111" 
   "11100" 
   "10000" 
   "11001" 
   "00010" 
   "01010") 
  
 (define example-result 198) 
  
  
 (module+ test 
  
   (require rackunit) 
  
   (check-equal? (aoc03a example-data) example-result) 
   (check-equal? (aoc03a) 3633500)) 
  
  
 $ raco test 03a.rkt 
 raco test: (submod "03a.rkt" test) 
 2 tests passed 
  
 $