Finish markov chain generation impl
* Markov chains will train and generate chains correctly now * Implement Markov.save_chains/0 * Add a couple more utils that help accomplish the above Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
This commit is contained in:
23
lib/util.ex
23
lib/util.ex
@@ -14,4 +14,27 @@ defmodule Omnibot.Util do
|
||||
def denotify_nick(nick) do
|
||||
String.graphemes(nick) |> Enum.join("\u200b")
|
||||
end
|
||||
|
||||
def weighted_random(items) when is_map(items) do
|
||||
Enum.to_list(items) |> weighted_random()
|
||||
end
|
||||
|
||||
def weighted_random([]), do: nil
|
||||
|
||||
def weighted_random(items) do
|
||||
value = items
|
||||
|> Enum.reduce(0, fn {_, weight}, total -> total + weight end)
|
||||
|> :rand.uniform()
|
||||
select_item(items, value)
|
||||
end
|
||||
|
||||
defp select_item([{item, _}], _), do: item
|
||||
|
||||
defp select_item([{item, weight} | _], index) when weight >= index, do: item
|
||||
|
||||
defp select_item([{_, weight} | tail], index), do: select_item(tail, index - weight)
|
||||
|
||||
def pad_trailing(list, _what, len) when length(list) >= len, do: list
|
||||
|
||||
def pad_trailing(list, what, len), do: pad_trailing(list ++ [what], what, len)
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user