Last active
February 13, 2017 23:42
-
-
Save DanCouper/681c8b1a1c8b8f50d2fddbec7b7fdaf0 to your computer and use it in GitHub Desktop.
Exploratory investigation of methods of creating dice rolls (first spike)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Dice do | |
@moduledoc """ | |
Fragile function that turns a string into a list of rolls - _e.g._ | |
> Dice.roll("2d6") | |
[4, 3] | |
> Dice.roll("d12") | |
[11] | |
""" | |
def roll(str) do | |
case String.split(str, "d") do | |
["", sides] -> roll(1, String.to_integer(sides)) | |
[n, sides] -> roll(String.to_integer(n), String.to_integer(sides)) | |
_ -> {:error, "some incorrect input"} | |
end | |
end | |
def roll(n, sides) do | |
1..n |> Enum.map(fn _ -> Enum.random(1..sides) end) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Roll do | |
@moduledoc """ | |
Creates a series of functions of the form `d{sides}(number_of_rolls)`. | |
Creates `Roll.d3\1`, `Roll.d4\1`, `Roll.d6\1`, `Roll.d8\1`, `Roll.d10\1`, `Roll.d12\1`, `Roll.d20\1` | |
> Roll.d3(2) | |
[1, 3] | |
> Roll.d6(6) | |
[3, 4, 4, 2, 6, 5] | |
""" | |
[3,4,6,8,10,12,20] |> Enum.each(fn sides -> | |
def unquote(:"d#{sides}")(n \\ 1) do | |
1..n |> Enum.map(fn _ -> Enum.random(1..unquote(sides)) end) | |
end | |
end) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment