Create a gist now

Instantly share code, notes, and snippets.

Embed
Euclidean Rhythm generator in Clojure
(defn split-seq [s]
"Extract a tail of all same elements: [1 1 0 0 0] -> [[1 1] [0 0 0]]"
(let [l (last s)]
(split-with #(not= l %) s)))
(defn recombine
"Distribute tail: [[1] [1] [1] [0] [0]] -> [[1 0] [1 0] [1]]"
([a b] [a b])
([a b c] [a b c])
([a b c & more]
(let [s (concat [a b c] more)
[head tail] (split-seq s)
recombined (map concat head tail)
r-len (count recombined)]
(if (empty? head) ;; even pattern (all supbatterns same)
s
(apply recombine (concat
recombined
(drop r-len (drop-last r-len s))))))))
(defn E [k n]
"Evenly distribute K beats among N subdivisions"
(let [seed (concat (repeat k [1]) (repeat (- n k) [0]))]
(flatten (apply recombine seed))))
;; output
> (E 3 6)
(1 0 1 0 1 0)
> (E 3 8)
(1 0 0 1 0 0 1 0)
> (E 4 6)
(1 0 1 1 0 1)
> (E 3 8)
(1 0 0 1 0 0 1 0)
> (E 2 6)
(1 0 0 1 0 0)
> (E 3 4)
(1 0 1 1)
> (E 5 11)
(1 0 0 1 0 1 0 1 0 1 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment