-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3.lisp
55 lines (50 loc) · 1.46 KB
/
3.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
(in-package #:cl-user)
;;; part 1
(defun mhd (n)
(if (= n 1)
0
(let* ((num (floor (ceiling (sqrt n)) 2))
(offset (mod (- n (expt (1- (* num 2)) 2)) (* 2 num))))
(+ num (abs (- offset num))))))
;;; part 2
(defun memoize (cache y x val)
(unless (gethash y cache)
(setf (gethash y cache) (make-hash-table)))
(setf (gethash x (gethash y cache)) val))
(defun recall (cache y x)
(if (gethash y cache)
(gethash x (gethash y cache) 0)
0))
(defun adjacent (cache yo xo)
(loop for y from (1- yo) to (1+ yo) summing
(loop for x from (1- xo) to (1+ xo) summing (recall cache y x))))
(defun spiral (n)
(let ((y 0)
(x 0)
(cache (make-hash-table)))
(memoize cache 0 0 1)
(loop named outer with c = 1
with l = 0 do
(when (= c n) (return-from outer (recall cache y x)))
(loop repeat (1+ l) do
(incf x)
(incf c)
(when (> (memoize cache y x (adjacent cache y x)) n)
(return-from outer (recall cache y x))))
(loop repeat (1+ l) do
(incf y)
(incf c)
(when (> (memoize cache y x (adjacent cache y x)) n)
(return-from outer (recall cache y x))))
(incf l)
(loop repeat (1+ l) do
(decf x)
(incf c)
(when (> (memoize cache y x (adjacent cache y x)) n)
(return-from outer (recall cache y x))))
(loop repeat (1+ l) do
(decf y)
(incf c)
(when (> (memoize cache y x (adjacent cache y x)) n)
(return-from outer (recall cache y x))))
(incf l))))