project-euler/shared.lisp

35 lines
1.1 KiB
Common Lisp
Raw Normal View History

2024-03-04 05:16:06 +00:00
(defmacro with-gensyms ((&rest names) &body body)
"Creates variables named NAMES via GENSYM and runs BODY"
`(let ,(loop for name in names collect `(,name (gensym)))
,@body))
2024-02-29 18:29:58 +00:00
(defun get-primes (max)
2024-03-04 20:47:02 +00:00
"Return a list of the first primes up to MAX"
2024-02-29 18:29:58 +00:00
(let ((primes nil)
(composites (make-array (1+ max) :initial-element 0)))
(loop for n from 2 upto max
do (when (= 0 (aref composites n))
(push n primes)
(loop for m from (* 2 n) upto max by n
do (incf (aref composites m)))))
(nreverse primes)))
2024-03-04 20:47:02 +00:00
(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)))