Markov Creativity

The above is an aleatoric composition in the style of J.S. Bach, produced automatically by my laptop in ~60 milliseconds. (You can hear a rendering here). The code to implement the algorithm comes to around 17 lines of Clojure:

(defn model-from-sequence
  "Returns a transition matrix of 'depth' from 'sequence'"
  [depth sequence]
  (loop [accum
chunks (partition (inc depth) 1 (seq sequence))] (if (seq? chunks) (let [chunk (first chunks) prefix (drop-last chunk) suffix (last chunk)] (recur (assoc accum prefix (conj (get accum prefix []) suffix)) (next chunks))) accum))) (defn chain "Returns a lazy Markov chain starting with 'current' using matrix 'trans'" [current trans] (if-let [transitions (trans current)] (cons (first current) (lazy-seq (chain (concat (rest current) [(rand-nth transitions)]) trans))) current))

This entry is part of my journal, published December 22, 2012, in New York.