Create a function that returns Tic-Tac-Toe game winners. You can represent the board with a tuple of nine elements, where each group of three items is a row. The return of the function should be a tuple. When we have a winner, the first element should be the atom :winner
, and the second should be the player. When we have no winner, the tuple should contain one item that is the atom :no_winner
. It should work like this:
Created
August 7, 2018 16:32
-
-
Save RyanHirsch/89fb0bc2d4f93184a0107f1136087d26 to your computer and use it in GitHub Desktop.
Learn Functional Programming with Elixir - Chapter 3 Pattern Matching Tic-Tac-Toe
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
TicTacToe.winner({ | |
:x, :o, :x, | |
:o, :x, :o, | |
:o, :o, :x | |
}) | |
# {:winner, :x} | |
TicTacToe.winner({ | |
:x, :o, :x, | |
:o, :x, :o, | |
:o, :x, :o | |
}) | |
# :no_winner |
You can pattern match with the tuples, you don't need to do the to_list first (as one option to keep the tuples)
defmodule TicTacToe do
def winner(board) do
check(board)
end
defp check({ w, w, w, _, _, _, _, _, _ }), do: { :winner, w }
defp check({ _, _, _, w, w, w, _, _, _ }), do: { :winner, w }
defp check({ _, _, _, _, _, _, w, w, w }), do: { :winner, w }
defp check({ w, _, _, w, _, _, w, _, _ }), do: { :winner, w }
defp check({ _, w, _, _, w, _, _, w, _ }), do: { :winner, w }
defp check({ _, _, w, _, _, w, _, _, w }), do: { :winner, w }
defp check({ w, _, _, _, w, _, _, _, w }), do: { :winner, w }
defp check({ _, _, w, _, w, _, w, _, _ }), do: { :winner, w }
defp check(_), do: { :no_winner }
end
This works but feels very brute force.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am struggling to find a way to do this while keeping the tuples. I keep wanting to
Tuple.to_list/1
it, then pattern match against the resulting list with multiplecheck/1
functions.