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.
2.3 KiB
2.3 KiB
Solution to p22
Solution
(require 'dash)
(with-temp-buffer
(insert-file-contents "input")
(goto-char (point-min))
(insert "(setq data '(")
(goto-char (point-max))
(insert "))")
(eval-buffer))
Define the operations needed to create the pseudorandom sequence
(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))))
This yields the solution to part 1
(apply #'+ (--map (-last-item (-iterate 'pseudo-next it 2001)) data))
19241711734
Create an alist with (quadruple . price)
(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)))
create-quadruples
(setq quadruples-data
(--map
(-quadruples (price-sequence it))
data))
2256
; 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)
((-2 1 -1 3) . 23)