aoc-2022/elisp/day-4/solution.el

77 lines
2.6 KiB
EmacsLisp
Executable File

#!/usr/bin/env -S emacs --script
;; -*- lexical-binding: t; -*-
;; Copyright (C) 2022
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
(add-to-list 'load-path default-directory)
(require 'ert)
(require 'advent-of-code)
(defun solution-parse-pair (s)
(let ((parts (string-split s "-")))
(cons (string-to-number (car parts))
(string-to-number (cadr parts)))))
(defun solution-parse-pairs (line)
(let ((unparsed-pairs (string-split line "," t)))
(list (solution-parse-pair (car unparsed-pairs))
(solution-parse-pair (cadr unparsed-pairs)))))
(defun solution-pair-contains? (a b)
(and (<= (car a) (car b))
(>= (cdr a) (cdr b))))
(defun solution-pair-overlaps? (a b)
(or (and (>= (car a) (car b))
(<= (car a) (cdr b)))
(and (>= (cdr a) (car b))
(<= (cdr a) (cdr b)))))
(defun solution-part-1 (input)
(let ((pairs (seq-map 'solution-parse-pairs input)))
(seq-count (lambda (pair)
(or (solution-pair-contains? (car pair) (cadr pair))
(solution-pair-contains? (cadr pair) (car pair))))
pairs)))
(defun solution-part-2 (input)
(let ((pairs (seq-map 'solution-parse-pairs input)))
(seq-count (lambda (pair)
(or (solution-pair-overlaps? (car pair) (cadr pair))
(solution-pair-overlaps? (cadr pair) (car pair))))
pairs)))
(ert-deftest solution-part-1-example ()
(should (equal (solution-part-1 (aoc-read-file-lines "example.txt")) 2)))
(ert-deftest solution-part-1 ()
(should (equal (solution-part-1 (aoc-read-file-lines "input.txt")) 644)))
(ert-deftest solution-part-2-example ()
(should (equal (solution-part-2 (aoc-read-file-lines "example.txt")) 4)))
(ert-deftest solution-part-2 ()
(should (equal (solution-part-2 (aoc-read-file-lines "input.txt")) 926)))
(when noninteractive
(ert-run-tests-batch))
;; Local Variables:
;; read-symbol-shorthands: (("solution-" . "advent-of-code-day-4-") ("aoc-" . "advent-of-code-"))
;; End: