Skip to content

Instantly share code, notes, and snippets.

@timsgardner
Last active August 29, 2015 14:10
Show Gist options
  • Save timsgardner/8e6e066e82c6c0961e72 to your computer and use it in GitHub Desktop.
Save timsgardner/8e6e066e82c6c0961e72 to your computer and use it in GitHub Desktop.
dynamic time warping
(ns dtw.core)
(defn distance [a b]
(Math/Pow (- a b) 2))
(defn dtw [s t]
(let [n (count s)
m (count t)
bottom (apply hash-map
(mapcat (fn [i] [[i 0] Double/PositiveInfinity])
(range 1 n)))
left (apply hash-map
(mapcat (fn [i] [[0 i] Double/PositiveInfinity])
(range 1 m)))
d (merge {[0 0] 0} bottom left)]
((reduce
(fn [acc [i j]]
(assoc acc
[i j]
(+ (distance (nth s i) (nth t j))
(min
(acc [(dec i) j])
(acc [i (dec j)])
(acc [(dec i) (dec j)])))))
d
(for [i (range 1 n)
j (range 1 m)]
[i j]))
[(dec n) (dec m)])))
@timsgardner
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment