Search code examples
arraysmultidimensional-arraylispclisp

Printing ith row jth column value in lisp


I am taking input N as number of rows of a 2D matrix in lisp, where each row can have maximum of 5 elements in it. So i make it like this. Now for eachrow as it can have any number of elements between 0 to 5. So I made a sepearte array to store size of each row of 2D matrix and increment it whenever I push any element in it

(setq myMatrix (make-array (list N 5)))

(setq sizeArray (make-list N:initial-element 0))

Now when I need add elements to any row I take input while the row has maximum elements or user himself exits to enter any more elements in that row. To add an element to ith row I do something like this :

(setf (aref myMatrix i (nth i sizeArray)) "Hi")
// Hi is just for example here
(setf (nth i sizeArray) (+ 1 (nth i sizeArray))) 

Now I want to print say ith row of this myMatrix Like this :

Item 1 : myMatrix[i][0]
Item 2 : myMatrix[i][1]..and so on

In direct way, I want jth value of ith row. How we can get this in lisp ?


Solution

  • Because you are using an array of lists how about:

    (defun element-of-matrix (matrix i j)
      (nth j (aref matrix i)))