Skip to content

Latest commit

 

History

History
139 lines (133 loc) · 3.57 KB

2022.04.org

File metadata and controls

139 lines (133 loc) · 3.57 KB

Day 04

Executing this code

If you have a lisp installation, emacs, org-mode, and org-babel support for lisp installed you can run this by:

  1. Starting slime (M-x slime)
  2. Typing C-c C-c in the block initialize.
  3. In the repl type (in-package :aoc-2022-04)
  4. Typing C-c C-c in the block answers

Initial stuffs

Packages to load

(unless (find-package :cl-ppcre)
  (ql:quickload "cl-ppcre"))
(unless (find-package :parseq)
  (ql:quickload "parseq"))
(unless (find-package :lparallel)
  (ql:quickload "lparallel"))
(unless (find-package :fiveam)
  (ql:quickload "fiveam"))
(unless (find-package :series)
  (ql:quickload "series"))
(unless (find-package :cl-permutation)
  (ql:quickload "cl-permutation"))
(unless (find-package :bordeaux-threads)
  (ql:quickload "bordeaux-threads"))

Create package for this day

<<packages>>
(defpackage :aoc-2022-04
  (:use :common-lisp
        :parseq
        :fiveam)
  (:export :problem-a
           :problem-b))
(in-package :aoc-2022-04)

Input

(defun process-stream (in)
  (loop for line = (read-line in nil)
        while line
        collect (cl-ppcre:register-groups-bind ((#'parse-integer a b c d))
                    ("(\\d+)-(\\d+),(\\d+)-(\\d+)" line)
                  (list a b c d))))
(defun read-input (file)
  (with-open-file (in file)
    (process-stream in)))
(defparameter *input*
  (read-input "input/04.txt"))

Part 1

(defun containsp (ranges)
  (destructuring-bind (a b c d) ranges
    (or (<= a c d b)
        (<= c a b d))))

(defun problem-a () (format t "Problem 04 A: ~a~%" (count-if #'containsp *input*)))

Part 2

(defun overlapp (ranges)
  (destructuring-bind (a b c d) ranges
    (and (<= a d) (<= c b))))

(defun problem-b () (format t "Problem 04 B: ~a~%" (count-if #'overlapp *input*)))

Putting it all together

<<read-input>>
<<input>>
<<initialize>>
<<structs>>
<<functions>>
<<input>>
<<problem-a>>
<<problem-b>>
(problem-a)
(problem-b)

Answer

Problem 04 A: 441
Problem 04 B: 861

Test Cases

(def-suite aoc.2022.04)
(in-suite aoc.2022.04)

(defparameter *sample-input*
  "2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8")

(test count-contains
  (with-input-from-string (in *sample-input*)
    (let ((ranges (process-stream in)))
      (is (= 2 (count-if #'containsp ranges))))))
(test count-overlaps
  (with-input-from-string (in *sample-input*)
    (let ((ranges (process-stream in)))
      (is (= 4 (count-if #'overlapp ranges))))))

(run! 'aoc.2022.04)

Test Results

Running test suite AOC.2022.04
 Running test COUNT-CONTAINS .
 Running test COUNT-OVERLAPS .
 Did 2 checks.
    Pass: 2 (100%)
    Skip: 0 ( 0%)
    Fail: 0 ( 0%)

Thoughts