Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure how to get the index of an item in a 2d list

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)

like image 307
user2150839 Avatar asked Dec 15 '22 06:12

user2150839


2 Answers

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.

like image 88
M Smith Avatar answered Feb 12 '23 08:02

M Smith


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)
like image 34
Jared314 Avatar answered Feb 12 '23 09:02

Jared314