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:
2020-07-15 16:25:25 -07:00
parent c43c075588
commit 4c93b42fdc
5 changed files with 150 additions and 21 deletions

View File

@@ -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