adventofcode

https://adventofcode.com/
Log | Files | Refs

puzzle_2.scm (1125B)


      1 (define (string-idx str chr)
      2   (- (string-length str) (length (memq chr (string->list str)))))
      3 
      4 (define (char-count str chr)
      5   (apply + (map (lambda (b) (if b 1 0)) (map (lambda (c) (char=? c chr)) (string->list str)))))
      6 
      7 (define (validate-passwords entries policy)
      8   (apply + (map (lambda (entry)
      9     (let
     10       ((idx (string-idx entry #-))
     11        (jdx (string-idx entry #space)))
     12       (let
     13         ((i (string->number (substring entry 0 idx)))
     14          (j (string->number (substring entry (+ idx 1) jdx)))
     15          (c (string-ref entry (+ jdx 1)))
     16          (s (substring entry (+ jdx 4) (string-length entry))))
     17         (policy s c i j))))
     18       entries)))
     19 
     20 (define policy-1
     21   (lambda (s c i j)
     22     (let ((count (char-count s c)))
     23       (if (and (>= count i) (<= count j)) 1 0))))
     24 
     25 (define policy-2
     26   (lambda (s c i j)
     27     (if (not (equal? (char=? (string-ref s (- i 1)) c)
     28         (char=? (string-ref s (- j 1)) c))) 1 0)))
     29 
     30 (load "read_lines.scm")
     31 (define input (read-lines "files/2.txt" (lambda (x) x)))
     32 
     33 (display (validate-passwords input policy-1)) (newline)
     34 (display (validate-passwords input policy-2)) (newline)