Wakaway

Build StatusHex versionHex downloadsInline docshex.pm

There're Walker's Alias Method and Weighted Choice that providing weighted random choice algorism in two ways.

Installation

If available in Hex, the package can be installed as:

  1. Add wakaway to your list of dependencies in mix.exs:
```elixir
def deps do
  [{:wakaway, "~> 0.5.0"}]
end
```

Usage

WalkersAliasMethod

alias Wakaway.WalkersAliasMethod

resource =
  WalkersAliasMethod.resource(
    [1, 2, 3, 50, 100, 200],
    [1, 2, 3, 50, 100, 200]
  )

# resource =
#   [s100: 100, s200: 200, s50: 50, s3: 3, s2: 2, s1: 1,]
#   |> WalkersAliasMethod.resource

# resource =
#   %{100 => 100, 200 => 200, 50 => 50, 3 => 3, 2 => 2, 1 => 1}
#   |> WalkersAliasMethod.resource

result =
  Enum.map(0..50, fn _ ->
    WalkersAliasMethod.choice(resource)
  end)
  |> Enum.sort(&(&1 > &2))

IO.inspect result
# [200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200,
#  200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200,
#  200, 200, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 50, 50, 50, 50, 50,
#  50, ...]

WeightedChoice

alias Wakaway.WeightedChoice

resource =
  WeightedChoice.resource(
    [1, 2, 3, 50, 100, 200],
    [1, 2, 3, 50, 100, 200]
  )

# resource =
#   [s100: 100, s200: 200, s50: 50, s3: 3, s2: 2, s1: 1,]
#   |> WeightedChoice.resource

# resource =
#   %{100 => 100, 200 => 200, 50 => 50, 3 => 3, 2 => 2, 1 => 1}
#   |> WeightedChoice.resource

result = Enum.map(0..50, fn _ ->
    WeightedChoice.choice(resource)
  end)
  |> Enum.sort(&(&1 > &2))

IO.inspect result
# [200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200,
#  200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200,
#  200, 200, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 50, 50, 50, 50, 50,
#  50, ...]

Simple ways

NOTE: This examples are slower than above way when they are called by users a lot of times.
iex(1)> item = %{100 => 100, 200 => 200, 50 => 50, 3 => 3, 2 => 2, 1 => 1}
%{1 => 1, 2 => 2, 3 => 3, 50 => 50, 100 => 100, 200 => 200}
iex(2)> Wakaway.walker_choice(item)
200
iex(3)> Wakaway.weighted_choice(item)
100

Example more