Refactor out matrix code

This commit is contained in:
scms 2024-03-04 12:47:02 -08:00
parent 9f88012e5b
commit 56ac4d366a
2 changed files with 22 additions and 19 deletions

View File

@ -1,27 +1,10 @@
;;; Approach: breadth-first search, storing position and sum in a cons
(defun read-matrix-from-file (path)
(let* ((list (mapcar (lambda (line)
(mapcar #'parse-integer
(uiop:split-string line :separator '(#\,))))
(uiop:read-file-lines path)))
(array (make-array (list (length list) (length (first list))))))
(loop for i upfrom 0
for row in list
do (loop for j upfrom 0
for value in row
do (setf (aref array i j) value)))
array))
;;; Approach: lowest sum first, visiting nodes once each, storing
;;; position and sum in a cons
(defparameter *matrix* (read-matrix-from-file "0081_matrix.txt"))
(defparameter *directions* '((1 0)
(0 1)))
(defun in-bounds-p (i max)
(and (>= i 0)
(< i max)))
(defun path-sum-two-ways ()
(let* ((dimensions (array-dimensions *matrix*))
(goal-position (mapcar #'1- dimensions))

View File

@ -4,6 +4,7 @@
,@body))
(defun get-primes (max)
"Return a list of the first primes up to MAX"
(let ((primes nil)
(composites (make-array (1+ max) :initial-element 0)))
(loop for n from 2 upto max
@ -12,3 +13,22 @@
(loop for m from (* 2 n) upto max by n
do (incf (aref composites m)))))
(nreverse primes)))
(defun read-matrix-from-file (path)
"Reads a two-dimensional array of integers into a matrix (2D array), from PATH"
(let* ((list (mapcar (lambda (line)
(mapcar #'parse-integer
(uiop:split-string line :separator '(#\,))))
(uiop:read-file-lines path)))
(array (make-array (list (length list) (length (first list))))))
(loop for i upfrom 0
for row in list
do (loop for j upfrom 0
for value in row
do (setf (aref array i j) value)))
array))
(defun in-bounds-p (i max)
"Returns non-NIL if I is on the interval [0, MAX)"
(and (>= i 0)
(< i max)))