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.
105 lines
2.3 KiB
105 lines
2.3 KiB
#+title: Solution to p22 |
|
|
|
* Solution |
|
|
|
#+begin_src emacs-lisp :results none |
|
(require 'dash) |
|
(with-temp-buffer |
|
(insert-file-contents "input") |
|
(goto-char (point-min)) |
|
(insert "(setq data '(") |
|
(goto-char (point-max)) |
|
(insert "))") |
|
(eval-buffer)) |
|
#+end_src |
|
|
|
Define the operations needed to create the pseudorandom sequence |
|
#+begin_src emacs-lisp :results none |
|
(defun mix (a b) |
|
(logxor a b)) |
|
|
|
(defun prune (a) |
|
(logand a 16777215)) |
|
|
|
(defun pseudo-next-1 (a) |
|
(prune (mix a (ash a 6)))) |
|
|
|
(defun pseudo-next-2 (a) |
|
(prune (mix a (ash a -5)))) |
|
|
|
(defun pseudo-next-3 (a) |
|
(prune (mix a (ash a 11)))) |
|
|
|
(defun pseudo-next (a) |
|
(pseudo-next-3 |
|
(pseudo-next-2 |
|
(pseudo-next-1 a)))) |
|
#+end_src |
|
|
|
This yields the solution to part 1 |
|
#+begin_src emacs-lisp |
|
(apply #'+ (--map (-last-item (-iterate 'pseudo-next it 2001)) data)) |
|
#+end_src |
|
|
|
#+RESULTS: |
|
: 19241711734 |
|
|
|
Create an alist with (quadruple . price) |
|
#+begin_src emacs-lisp :results none |
|
(defun price-sequence (seed) |
|
(--map (mod it 10) (-iterate 'pseudo-next seed 2001))) |
|
|
|
(defun take-quadruples (l) |
|
(-zip-lists l (cdr l) (cddr l) (cdddr l))) |
|
|
|
(defun create-quadruples (s) |
|
(-zip-pair (take-quadruples |
|
(-zip-with '- (cdr s) s)) |
|
(cddddr s))) |
|
#+end_src |
|
|
|
#+RESULTS: |
|
: create-quadruples |
|
|
|
|
|
#+begin_src emacs-lisp :results none |
|
(setq quadruples-data |
|
(--map |
|
(-quadruples (price-sequence it)) |
|
data)) |
|
#+end_src |
|
|
|
#+RESULTS: |
|
: 2256 |
|
|
|
#+begin_src emacs-lisp |
|
; this seems super slow; it is not needed if we concatenate lists |
|
; properly |
|
(defun normalize-alist (al) |
|
"Remove from the alist the secondary occurrences of each key" |
|
(--filter (eq it (assoc (car it) al)) al)) |
|
|
|
(defun sum-stuff (b a) |
|
"A and B are two alists. " |
|
(append |
|
(--map (cons (car it) |
|
(+ (cdr it) |
|
(or (cdr (assoc (car it) b)) 0))) |
|
a) |
|
b)) |
|
(native-compile 'sum-stuff); just in case |
|
|
|
(setq summed-quadruples |
|
(let ((index 0)) |
|
(--reduce (progn |
|
(message (format "Processing %d/2256" index)) |
|
(setq index (+ 1 index)) |
|
(sum-stuff acc it)) |
|
quadruples-data))) |
|
|
|
(--max-by (> (cdr it) (cdr other)) |
|
summed-quadruples) |
|
#+end_src |
|
|
|
#+RESULTS: |
|
: ((-2 1 -1 3) . 23)
|
|
|