Skip to content

Instantly share code, notes, and snippets.

@jadlr
Last active August 5, 2017 13:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jadlr/aea578d8166bb6b24203886125df9d04 to your computer and use it in GitHub Desktop.
A game my son likes to play https://de.wikipedia.org/wiki/Bataille_royale
defmodule BatailleRoyale do
@cards 0..7 |> Enum.to_list |> List.duplicate(4) |> List.flatten
def times(n) do
results =
1..n
|> Enum.map(fn _ -> play() end)
|> Enum.map(fn {_, _, moves} -> moves end)
IO.puts(~s/min moves: #{Enum.min(results)}/)
IO.puts(~s/max moves: #{Enum.max(results)}/)
end
def play do
{player1, player2} =
@cards
|> Enum.shuffle
|> Enum.split(16)
move(player1, [], player2, [], true, [], 0)
end
defp move([], [], [], [], _, _, moves), do: {:ok, :both_won, moves}
defp move([], [], _, _, _, _, moves), do: {:ok, :player_two_won, moves}
defp move(_, _, [], [], _, _, moves), do: {:ok, :player_one_won, moves}
defp move([], w1, d2, w2, check, acc, moves), do: move(Enum.shuffle(w1), [], d2, w2, check, acc, moves)
defp move(d1, w1, [], w2, check, acc, moves), do: move(d1, w1, Enum.shuffle(w2), [], check, acc, moves)
defp move([c1|t1], w1, [c2|t2], w2, true, acc, moves) when c1 > c2 do
move(t1, [c1, c2 | acc] ++ w1, t2, w2, true, [], moves + 1)
end
defp move([c1|t1], w1, [c2|t2], w2, true, acc, moves) when c1 < c2 do
move(t1, w1, t2, [c1, c2 | acc] ++ w2, true, [], moves + 1)
end
defp move([c1|t1], w1, [c2|t2], w2, true, acc, moves) when c1 == c2 do
move(t1, w1, t2, w2, false, [c1, c2 | acc], moves + 1)
end
defp move([c1|t1], w1, [c2|t2], w2, false, acc, moves) do
move(t1, w1, t2, w2, true, [c1, c2 | acc], moves + 1)
end
end
@jadlr
Copy link
Author

jadlr commented Aug 5, 2017

Sometimes this game takes forever. I wanted to see how bad this can get 😄

iex(1)> BatailleRoyale.times(100)
min moves: 20
max moves: 652
:ok
iex(2)> BatailleRoyale.times(1000)
min moves: 18
max moves: 800
:ok
iex(3)> BatailleRoyale.times(10000)
min moves: 16
max moves: 1180
:ok
iex(4)> BatailleRoyale.times(100000)
min moves: 16
max moves: 1316

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