[p5] Part 2 done

master
Jacopo De Simoi 3 months ago
parent 507d4751a7
commit b59b20656b
  1. 23
      p5/p5.org

@ -3,7 +3,7 @@
First load the data as a list of cons cells (start . end)
#+begin_src emacs-lisp :results none
(with-temp-buffer
(insert-file-contents "input-test")
(insert-file-contents "input")
(advent/replace-multiple-regex-buffer
'(
("^\\([0-9]*\\)-\\([0-9]*\\)$" . "(\\1 . \\2)")
@ -15,16 +15,31 @@ First load the data as a list of cons cells (start . end)
(eval-buffer))
#+end_src
This is for part 1
#+begin_src emacs-lisp
(length
(length
(-filter (lambda (id)
(--any (and (>= id (car it))
(<= id (cdr it)))
#+end_src
For part 2, sort and merge the ranges (when they are overlapping or
adjacent), then sum their lengths
#+begin_src emacs-lisp
(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)))
#+end_src
#+RESULTS:
: 744
#+RESULTS:
: 347468726696961

Loading…
Cancel
Save