Reputation: 1266
I want to create a map where the keys are characters in the string and the values of each key are lists of positions of given character in the string.
Upvotes: 0
Views: 246
Reputation: 17859
a bit shorter variant:
(defn process [^String s]
(group-by #(.charAt s %) (range (count s))))
user> (process "asdasdasd")
;;=> {\a [0 3 6], \s [1 4 7], \d [2 5 8]}
notice that indices here are sorted
Upvotes: 6
Reputation: 1688
I am sure there are several solutions for this. My first thought was use map-indexed
to get a list of [index character]
then reduce
the collection in to a map.
(defn char-index-map [sz]
(reduce
(fn [accum [i ch]]
(update accum ch conj i))
{}
(map-indexed vector sz)))
(char-index-map "aabcab")
;;=> {\a (4 1 0), \b (5 2), \c (3)}
Upvotes: 4