Skip to content

Commit

Permalink
Added function for randomly selecting a key in a stochastic collectio…
Browse files Browse the repository at this point in the history
…n of pairs

This is how I will select states and emissions randomly
  • Loading branch information
dwysocki committed Mar 17, 2015
1 parent 40a91d5 commit 6f2d8eb
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/hidden_markov_music/random.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
(ns hidden-markov-music.random)

(defn rand*
"Returns a random floating point number between 0 (exclusive) and
n (default 1) (inclusive)."
([]
(rand* 1.0))
([n]
(- n (rand n))))

(defn select-random-key
"Takes a collection of `[key prob]` pairs, whose `prob`s sum to 1.0, and
selects a `key` randomly based on its `prob`."
[key->prob]
(loop [key->prob key->prob
selection-index (rand*)]
(let [[k p] (first key->prob)
new-selection-index (- selection-index p)]
(if (pos? new-selection-index)
(recur (rest key->prob) new-selection-index)
k))))

0 comments on commit 6f2d8eb

Please sign in to comment.