So, I wrote the following program to determine the max element in a 2D array using LISP. Note, this is my first time using the language, so I am unfamiliar with many aspects.
The function should return the coordinates of the largest element in row-major order. In the below example, the largest element, 7, is found at index (2, 4). However, when the program is executed, it returns (3, 15).
It seems to be starting the index at 1, rather than 0, for the row. Additionally, it seems to be counting all indexes up to 15, where the max element is found. I am unsure how to fix this issue.
(defun find-max-location (x)
(let (
(maxval -100)
(loc nil)
(cur 0)
(cur2 0)
(k 1)
(l 1)
(f 0))
(loop for i in x do
(loop for j in i do
(if (> j maxval)
(progn
(setf cur k)
(setf cur2 l)
(setf maxval j))
)
(setf l (+ l 1))
)
(setf k (+ k 1))
)
(list cur cur2)))
(find-max-location '((0 1 0 0 1) (0 2 2 0 0) (3 0 1 4 7) (0 1 2 0 0) (1 2 1 0 3)))
It seems that you're thinking about this in a very procedural manner. Recursion is your friend here.
How would we find the max and its position in a simple list? We'd recursively count up from
0, evaluating each element to see if it's greater than the currentmaxor ifmaxhasn't yet been set. We'd use themaxparameter to the function to update this information. Hitting the end of the list we'd return themax.Prints:
This logic can be adapted to find the column where a max value occurs. A starting point would be to map this function to your list of rows.
Prints: