WeightedRandom.Die (weighted_random v1.0.0-rc.1)

Copy Markdown View Source

A struct and related functions to represent a single die, with any number of sides and weights.

iex> :rand.seed(:exsplus, {123, 321, 213})
iex> alias WeightedRandom.Die
iex> d = Die.new(%{sides: 6, weights: [%{target: 3, amount: 10}]})
iex> d = Die.roll(d)
iex> d.result
3

Summary

Functions

Given an existing Die struct, add some weights

Manually create an individual die struct.

Reroll a die, randomly picking one of the sides, using the given weights to influence the result.

Types

t()

@type t() :: %WeightedRandom.Die{
  preprocessed: struct(),
  result: any(),
  sides: integer(),
  weights: list()
}

Functions

add_weight(die, weights)

@spec add_weight(t(), [WeightedRandom.Utils.Types.weight_spec()]) :: t()
@spec add_weight(t(), WeightedRandom.Utils.Types.weight_spec()) :: t()

Given an existing Die struct, add some weights

Examples

iex> :rand.seed(:exsplus, {123, 321, 213})
iex> die = Die.new(%{sides: 12})
iex> die = Die.add_weight(die, [%{target: 5, amount: 50}])
iex> Die.roll(die).result
5

new(body, opts \\ [])

Manually create an individual die struct.

Eamples

iex> die = Die.new(%{sides: 6})
iex> die.result >= 1 and die.result <= 6
true

Takes a single map as an argument, with the following keys:

  • :sides (pos_integer/0) - The number of faces on a polyhedral die. This is used to generate 1-indexed outcomes The default value is 6.

  • :weights - List of weights. See details. The default value is [].

roll(die)

@spec roll(t()) :: t()

Reroll a die, randomly picking one of the sides, using the given weights to influence the result.

Examples

iex> :rand.seed(:exsplus, {123, 321, 213})
iex> die = Die.new(%{sides: 6, weights: []})
iex> die.result
3
iex> Die.roll(die).result
6