hi there,
Is there something like the position function but for multidimensional arrays? Something that takes the array and another argument, if the argument is an element of the array, it would return its index.
Any help would be appreciated.
trilepton wrote:Is there something like the position function but for multidimensional arrays? Something that takes the array and another argument, if the argument is an element of the array, it would return its index.
(defun array-indices (row-major-index dimensions)
"Recursively calculate the indices from the row major index."
(let ((remaining (rest dimensions)))
(if remaining
(multiple-value-bind (index remainder)
(floor row-major-index (reduce #'* remaining))
(cons index (array-indices remainder remaining)))
(cons row-major-index nil))))
(defun array-position (item array &key (test #'eql))
"Return the position of the first occurrence of item in array."
(check-type array array)
(dotimes (index (array-total-size array))
(when (funcall test item (row-major-aref array index))
(return-from array-position
(array-indices index (array-dimensions array))))))
(defun array-position (item array &rest position-parameters)
(let ((temp-array (make-array (reduce #'* (array-dimensions array)) :displaced-to array)))
(array-indices (apply #'position item temp-array position-parameters)
(array-dimensions array))))
Ramarren wrote:You can also do:
- Code: Select all
(defun array-position (item array &rest position-parameters)
(let ((temp-array (make-array (reduce #'* (array-dimensions array)) :displaced-to array)))
(array-indices (apply #'position item temp-array position-parameters)
(array-dimensions array))))
Not that this is a very good idea, but really, how often does searching in an array makes sense?
gugamilare wrote:...so it shouldn't be fast.
findinglisp wrote:Just a quibble, but I don't know of any function that "shouldn't be fast." There are many that are not required to be fast because they are only used infrequently, but that's not quite the same thing.
Users browsing this forum: No registered users and 7 guests