Using the list comprehension (for) along with a helper function
(index)
(def y (list "#####" "#...O" "#.#.#" "I.#.#" "#...#" "#####"))
(defn index [s] (map #(vector %1 %2) s (range)))
(defn index-maze [maze-str]
(reduce conj {}
(for [r (index maze-str)
c (index (first r))]
{[(second r) (second c)] (first c)})))
(index-maze y)
The index function takes a sequence and returns a sequence of vectors
with the value and the index.
(index [:a :b :c])
=> ([:a 0] [:b 1] [:c 2])
A similar function exists in the clojure contrib seq-utils:
http://richhickey.github.com/clojure-contrib/seq-utils-api.html#clojure.contrib.seq-utils/indexed
The for call then uses this index function to create the index for
rows and columns. Then use reduce to create a map with all the
entries.
On Aug 12, 6:49 am, johanmartinsson <[email protected]>
wrote:
> Hello,
>
> I'm trying to find an elegant way of indexing a two-dimensional sequence
> with the coordinates as keys.
>
> The input is something like.
>
> (
>
> "#####"
>
> "#...O"
>
> "#.#.#"
>
> "I.#.#"
>
> "#...#"
>
> "#####")
>
> The midje test below indicates what kind of behaviour I'm looking for. I
> can't come up with a solution that is elegant. I'm sure there are better
> ways to do this, especially in such a sequence oriented language as clojure.
> Would someone please give me a hand here?
>
> (defn- index-maze [str-maze]
>
> (let [width (count (first str-maze))
>
> symbols (flatten (map seq str-maze))
>
> total-size (count symbols)]
>
> (apply conj
>
> (for [position (range total-size)
>
> :let [row (quot position width)
>
> column (mod position width)
>
> sym (nth symbols position)]]
>
> {[row column] sym}))))
>
> (fact
>
> "makes a map with the coordinates as keys symbols as values"
>
> (index-maze '("#I#"
>
> "#O#")) => (in-any-order {
>
> [0 0] \#
>
> [0 1] \I
>
> [0 2] \#
>
> [1 0] \#
>
> [1 1] \O
>
> [1 2] \#}))
>
> Regards
>
> Johan Martinsson
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en