Skip to content

Instantly share code, notes, and snippets.

@aschiavon91
Last active March 11, 2022 19:03
Show Gist options
  • Select an option

  • Save aschiavon91/66e0b7dcb7b48be984fd0803c8adfc38 to your computer and use it in GitHub Desktop.

Select an option

Save aschiavon91/66e0b7dcb7b48be984fd0803c8adfc38 to your computer and use it in GitHub Desktop.
Elixir random game number generator
defmodule MegaGen do
@min_choice 1
@max_choice 60
@valid_choices @min_choice..@max_choice
@total_choices 6
defguard game_complete(total_choices, acc) when map_size(acc.map) == total_choices
def min_choice, do: @min_choice
def max_choice, do: @max_choice
def valid_choices, do: @valid_choices
def total_choices, do: @total_choices
def game(total_choices \\ @total_choices, valid_choices \\ @valid_choices, acc \\ MapSet.new())
def game(total_choices, _valid_choices, acc) when game_complete(total_choices, acc) do
acc.map
|> Map.keys()
|> IO.inspect(charlists: :as_lists)
end
def game(total_choices, valid_choices, acc) do
new = random(valid_choices, acc)
if MapSet.member?(acc, new) do
game(total_choices, valid_choices, acc)
else
game(total_choices, valid_choices, MapSet.put(acc, new))
end
end
defp random(valid_choices, invalid_choices) do
valid_choices
|> Enum.to_list()
|> MapSet.new()
|> MapSet.difference(invalid_choices)
|> Enum.random()
end
end
System.argv()
|> then(fn
[total_choices, min_choice, max_choice] ->
[
String.to_integer(total_choices),
String.to_integer(min_choice)..String.to_integer(max_choice)
]
[total_choices, max_choice] ->
[String.to_integer(total_choices), MegaGen.min_choice()..String.to_integer(max_choice)]
[total_choices] ->
[String.to_integer(total_choices), MegaGen.valid_choices()]
[] ->
[MegaGen.total_choices(), MegaGen.valid_choices()]
end)
|> then(&apply(MegaGen, :game, &1))
@aschiavon91
Copy link
Author

Works great for MegaSena, LotoFácil and other brazilian loto games!

Running

## Generate 6 numbers
$ elixir run.exs
[6, 10, 25, 26, 38, 44]

## Generate N numbers, when 10 is the N
$ elixir run.exs 10
[6, 7, 19, 25, 32, 34, 38, 40, 53, 55]

## Generate N numbers, from 1 to M
## when 10 is the N and M is the 100.
$ elixir run.exs 10 100
[17, 21, 41, 45, 49, 52, 68, 70, 94, 100]

## Generate N numbers, from M to O
## when 6 is the N, M is the 10 and O is the 150.
$ elixir run.exs 6 10 150
[16, 19, 30, 72, 101, 111]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment