If I have a list like...
(def test [[1 2 3]
[4 5 6]
[7 8 9]])
and I want the index of 5 (which would be (1,1)) how would I do that? so (find 5 test) = (1,1)
Using list comprehension (for) the the list of all matching positions can be found:
(def test [[1 2 3][4 5 6][7 8 9]])
(for [[x row] (map-indexed vector test)
[y val] (map-indexed vector row)
:when (= 5 val)]
[x y])
=> ([1 1])
EDIT: Using destructuring works for the 'for' function.
I don't think there is a builtin function for that operation, but it shouldn't be hard to write one.
You could flatten the nested vectors, into a single list, then search, take the resulting index and split out the x and y coordinates, using the length of the first nested vector.
(defn find2d [data item]
(let [n (count (first data))
i (.indexOf (flatten data) item)]
(if (pos? i)
(list (quot i n) (mod i n)))))
(find2d data 5) ;=> (1 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With