Created
December 1, 2016 13:40
-
-
Save terakilobyte/660f9afdc2635a1cd3b33c13fd8b4708 to your computer and use it in GitHub Desktop.
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 Tictactoe do | |
@winning_positions [{0, 1, 2}, {0, 3, 6}, {0, 4, 8}, {1, 4, 7}, {2, 5, 8}, {3, 4, 5}, {6, 7, 8}, {2, 4, 6}] | |
def winning_position?(board) do | |
case winning?(board) do | |
{false, _} -> {false, nil} | |
winner -> winner | |
end | |
end | |
defp winning?(board) do | |
Enum.reduce( | |
@winning_positions, | |
{false, nil}, | |
fn({x, y, z}, acc) -> iterate_positions({x, y, z}, board, acc) end | |
) | |
end | |
defp iterate_positions(_, _, {true, winner}), do: {true, winner} | |
defp iterate_positions({x, y, z}, board, {false, _}) do | |
case Enum.at(board, x) do | |
"" -> {false, nil} | |
nil -> {false, nil} | |
_ -> {Enum.at(board, x) == Enum.at(board, y) and Enum.at(board, x) == Enum.at(board, z), Enum.at(board, x)} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment