aeter
aeter

Reputation: 12720

Unflattening a sequence to sequences of repeating elements (clojure)

In Clojure, how do you partition a sequence to subsequences of repeating elements? E.g. :

[1 2 2 3 3 3 4 2 2 1 1 1]

to

[[1] [2 2] [3 3 3] [4] [2 2] [1 1 1]]

I've been playing around with some examples trying to understand clojure better, and was stuck on this one for some time.

Upvotes: 9

Views: 387

Answers (2)

amalloy
amalloy

Reputation: 92147

(map (juxt count first) (partition-by identity [1 1 1 3 2 2]))

((3 1) (1 3) (2 2))

Three ones, then one three, followed by two twos!

Upvotes: 2

Brian Carper
Brian Carper

Reputation: 73006

user> (partition-by identity [1 2 2 3 3 3 4 2 2 1 1 1])
((1) (2 2) (3 3 3) (4) (2 2) (1 1 1))

user> (vec (map vec (partition-by identity [1 2 2 3 3 3 4 2 2 1 1 1])))
[[1] [2 2] [3 3 3] [4] [2 2] [1 1 1]]

Upvotes: 14

Related Questions