Skip to content

Instantly share code, notes, and snippets.

@terakilobyte
Created December 1, 2016 02:08
Show Gist options
  • Save terakilobyte/5835243099675a6f775891396768e415 to your computer and use it in GitHub Desktop.
Save terakilobyte/5835243099675a6f775891396768e415 to your computer and use it in GitHub Desktop.
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
Enum.reduce(@winning_positions, false, fn({x, y, z}, acc) -> iterate_positions({x, y, z}, board) || acc end)
end
defp iterate_positions({x, y, z}, board) do
Enum.at(board, x) == Enum.at(board, y) and Enum.at(board, x) == Enum.at(board, z)
end
end
@terakilobyte
Copy link
Author

@winning_boards [
["X", "X", "X", "", "", "", "", "", ""],
["", "", "", "X", "X", "X", "", "", ""],
["", "", "", "", "", "", "X", "X", "X"],
["X", "", "", "", "X", "", "", "", "X"],
["X", "", "", "X", "", "", "X", "", ""],
["", "X", "", "", "X", "", "", "X", ""],
["", "", "X", "", "", "X", "", "", "X"],
["", "", "X", "", "X", "", "X", "", ""]
]

test "finds all winning positions" do
assert Enum.all?(@winning_boards, &Tictactoe.winning_position?/1)
end

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