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.
 

4.2 KiB

Solution to p10

Load the file into a list of lines

(require 'dash)
  (with-temp-buffer
    (insert-file-contents "input")
    (goto-char (point-min))
    (replace-regexp "^" "\"")
       (goto-char (point-min))
       (replace-regexp "$" "\"")
    (goto-char (point-min))
    (insert "(setq data '(")
    (goto-char (point-max))
    (insert "))")
    (eval-buffer))

and split into a list of list of heights, calculating height and width

  (setq data-heights (-map (lambda (str) (--map (- (string-to-char it) ?0) (split-string str "\\|.+" t)))
			 data)
	  height (length data-heights)
	  width (length (car data-heights)))
41

here we define some helper functions

  (defun acceptable-p (p)
    (let ((x (car p))
	  (y (cadr p)))
      (and (>= x 0) (>= y 0) (< x width) (< y height)) ))

  (defun neighbours (p)
    (let ((x (car p))
	  (y (cadr p)))
      (-filter #'acceptable-p
	       (-map (lambda (q) (list (+ x (car q)) (+ y (cadr q)))) '((+1 0) (-1 0) (0 1) (0 -1))))))

  (defun height (p)
    (nth (car p) (nth (cadr p) data-heights)))
height

This yields the coordinates of the trailheads

  (setq trail-heads (-map #'cadr
	  (--filter (eq (car it) 0)
		    (-mapcat #'identity
			     (-map-indexed (lambda (y l) (-map-indexed (lambda (x el) (list el (list x y))) l)) data-heights)))))
2 0
14 0
17 0
22 0
33 0
35 0
12 1
18 1
32 1
1 2
3 2
35 2
6 3
14 3
19 3
24 3
26 3
37 3
7 4
14 4
20 4
21 4
23 4
28 4
30 4
36 4
38 4
0 5
24 5
29 5
33 5
7 6
9 6
14 6
19 6
25 6
26 6
28 6
38 6
39 6
2 7
6 7
4 8
17 8
27 8
35 8
40 8
8 9
12 9
20 9
39 9
8 10
9 10
27 10
31 10
33 10
0 11
12 11
24 11
39 11
0 12
1 12
4 12
8 12
10 12
13 12
25 12
14 13
22 13
27 13
37 13
10 14
13 14
15 14
33 14
36 14
5 15
17 15
21 15
32 15
16 16
20 16
31 16
38 16
8 17
9 17
19 17
0 18
7 18
17 18
19 18
28 18
34 18
10 19
17 19
23 19
30 19
32 19
33 19
2 20
7 20
13 20
39 20
5 21
6 21
19 21
30 21
0 22
7 22
16 22
22 22
24 22
29 22
30 22
35 22
37 22
12 23
22 23
29 23
32 23
22 24
23 24
38 24
3 25
10 25
21 25
26 25
31 25
36 25
39 25
40 26
6 27
11 27
16 27
23 27
28 27
31 27
33 27
39 27
8 28
18 28
0 29
1 29
3 29
11 29
37 29
2 30
19 30
21 30
31 30
8 31
15 31
26 31
27 31
4 32
5 32
7 32
11 32
12 32
29 32
38 32
13 33
24 33
40 33
5 34
7 34
20 34
32 34
13 35
15 35
21 35
29 35
34 35
37 35
39 35
40 35
26 36
29 36
33 36
39 36
10 37
13 37
15 37
17 37
38 37
1 38
25 38
2 39
39 39
1 40
2 40
4 40
14 40
22 40
23 40
24 40

these follow the trails to the top, calculating the two properties of each trailhead

     (defun tails (p h)
       (when (eq (height p) h)
	 (if (eq h 9) (list p)
	   (--mapcat (tails it (+ 1 h)) (neighbours p)))))
     (defun score (p)
       (length (-distinct (tails p 0))))
     (defun rating (p)
       (length (tails p 0)))

  (-reduce #'+ (-map #'score trail-heads))
  (-reduce #'+ (-map #'rating trail-heads))
1186