You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1.3 KiB

Solution to p5

First load the data as a list of cons cells (start . end)

  (with-temp-buffer
    (insert-file-contents "input")
    (advent/replace-multiple-regex-buffer
     '(
       ("^\\([0-9]*\\)-\\([0-9]*\\)$" . "(\\1 . \\2)")
       ("^$" . ") ids '(")))
    (goto-char (point-min))
    (insert "(setq ranges '(")
    (goto-char (point-max))
    (insert "))")
    (eval-buffer))

This is for part 1

  (-count (lambda (id)
            (--any (and (>= id (car it))
                        (<= id (cdr it)))
                   ranges))
          ids)
744

For part 2, sort and merge the ranges (when they are overlapping or adjacent), then sum their lengths

  (setq sorted-ranges (--sort (< (car it) (car other)) ranges))

  (defun merge-ranges (li)
    (-reduce (lambda (a b)
               (let* ((a (if (listp (cdr a)) a (list a)))
                      (aa (car a)))
                 (if (>= (1+ (cdr aa)) (car b))
                     (cons (cons (car aa) (max (cdr aa) (cdr b))) (cdr a))
                   (cons b a))))
             li))

  (-sum (--map (- (cdr it) (car it) -1)
               (merge-ranges sorted-ranges)))
347468726696961