Skip to content

New practice exercise state-of-tic-tac-toe #1115

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Apr 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions bin/bootstrap_practice_exercise.exs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,38 @@ end

Mix.Generator.create_file("exercises/practice/#{exercise}/mix.exs", mix)

# .gitignore
gitignore = """
# The directory Mix will write compiled artifacts to.
/_build/

# If you run "mix test --cover", coverage assets end up here.
/cover/

# The directory Mix downloads your dependencies sources to.
/deps/

# Where third-party dependencies like ExDoc output generated docs.
/doc/

# Ignore .fetch files in case you like to edit your project deps locally.
/.fetch

# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump

# Also ignore archive artifacts (built via "mix archive.build").
*.ez

# Ignore package tarball (built via "mix hex.build").
#{exercise_snake_case}-*.tar

# Temporary files, for example, from tests.
/tmp/
"""

Mix.Generator.create_file("exercises/practice/#{exercise}/.gitignore", gitignore)

# test/test_helper.exs
test_helper = """
ExUnit.start()
Expand Down
19 changes: 19 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2386,6 +2386,25 @@
],
"difficulty": 6
},
{
"slug": "state-of-tic-tac-toe",
"name": "State of Tic Tac Toe",
"uuid": "905ac84d-7ba1-4208-bee1-55d8efde0c01",
"prerequisites": [
"strings",
"tuples",
"atoms",
"cond",
"lists",
"enum",
"maps",
"list-comprehensions",
"case",
"charlists"
],
"practices": ["cond"],
"difficulty": 6
},
{
"slug": "variable-length-quantity",
"name": "Variable Length Quantity",
Expand Down
99 changes: 99 additions & 0 deletions exercises/practice/state-of-tic-tac-toe/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Instructions

In this exercise, you're going to implement a program that determines the state of a [tic-tac-toe](https://en.wikipedia.org/wiki/Tic-tac-toe) game.
(_You may also know the game as "noughts and crosses" or "Xs and Os"._)

The games is played on a 3×3 grid.
Players take turns to place `X`s and `O`s on the grid.
The game ends when one player has won by placing three of marks in a row, column, or along a diagonal of the grid, or when the entire grid is filled up.

In this exercise, we will assume that `X` starts.

It's your job to determine which state a given game is in.

There are 3 potential game states:

- The game is **ongoing**.
- The game ended in a **draw**.
- The game ended in a **win**.

If the given board is invalid, throw an appropriate error.

If a board meets the following conditions, it is invalid:

- The given board cannot be reached when turns are taken in the correct order (remember that `X` starts).
- The game was played after it already ended.

## Examples

### Ongoing game

```text
| |
X | |
___|___|___
| |
| X | O
___|___|___
| |
O | X |
| |
```

### Draw

```text
| |
X | O | X
___|___|___
| |
X | X | O
___|___|___
| |
O | X | O
| |
```

### Win

```text
| |
X | X | X
___|___|___
| |
| O | O
___|___|___
| |
| |
| |
```

### Invalid

#### Wrong turn order

```text
| |
O | O | X
___|___|___
| |
| |
___|___|___
| |
| |
| |
```

#### Continued playing after win

```text
| |
X | X | X
___|___|___
| |
O | O | O
___|___|___
| |
| |
| |
```
4 changes: 4 additions & 0 deletions exercises/practice/state-of-tic-tac-toe/.formatter.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
26 changes: 26 additions & 0 deletions exercises/practice/state-of-tic-tac-toe/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# The directory Mix will write compiled artifacts to.
/_build/

# If you run "mix test --cover", coverage assets end up here.
/cover/

# The directory Mix downloads your dependencies sources to.
/deps/

# Where third-party dependencies like ExDoc output generated docs.
/doc/

# Ignore .fetch files in case you like to edit your project deps locally.
/.fetch

# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump

# Also ignore archive artifacts (built via "mix archive.build").
*.ez

# Ignore package tarball (built via "mix hex.build").
state_of_tic_tac_toe-*.tar

# Temporary files, for example, from tests.
/tmp/
22 changes: 22 additions & 0 deletions exercises/practice/state-of-tic-tac-toe/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"authors": [
"jiegillet"
],
"contributors": [
"angelikatyborska"
],
"files": {
"solution": [
"lib/state_of_tic_tac_toe.ex"
],
"test": [
"test/state_of_tic_tac_toe_test.exs"
],
"example": [
".meta/example.ex"
]
},
"blurb": "Determine the game state of a match of Tic Tac Toe.",
"source": "Created by Sascha Mann for the Julia track of the Exercism Research Experiment.",
"source_url": "https://github.com/exercism/research_experiment_1/tree/julia-dev/exercises/julia-1-a"
}
51 changes: 51 additions & 0 deletions exercises/practice/state-of-tic-tac-toe/.meta/example.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
defmodule StateOfTicTacToe do
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My solution (without looking at yours first)

defmodule StateOfTicTacToe do
  @symbol_map %{
    "X" => :x,
    "O" => :o
  }

  @doc """
  Determine the state a game of tic-tac-toe where X starts.
  """
  @spec gamestate(board :: String.t()) :: {:ok, :win | :ongoing | :draw} | {:error, String.t()}
  def gamestate(board) do
    board
    |> parse_board()
    |> check_state()
  end

  defp parse_board(board) do
    board
    |> String.split("\n", trim: true)
    |> Enum.map(fn row ->
      String.split(row, "", trim: true)
      |> Enum.map(&@symbol_map[&1])
    end)
  end

  defp check_state(parsed_board) do
    case validate_state(parsed_board) do
      :ok -> find_winners(parsed_board)
      {:error, error} -> {:error, error}
    end
  end

  defp frequencies(parsed_board) do
    plays = parsed_board |> List.flatten() |> Enum.filter(& &1)
    Map.merge(%{x: 0, o: 0}, Enum.frequencies(plays))
  end

  defp validate_state(parsed_board) do
    frequencies = frequencies(parsed_board)

    cond do
      frequencies.o > frequencies.x -> {:error, "Wrong turn order: O started"}
      frequencies.x > frequencies.o + 1 -> {:error, "Wrong turn order: X went twice"}
      true -> :ok
    end
  end

  defp find_winners(parsed_board) do
    full_board? = parsed_board |> List.flatten() |> Enum.reject(& &1) |> Kernel.==([])

    row_winners = row_winners(parsed_board)
    column_winners = column_winners(parsed_board)
    diagonal_winners = diagonal_winners(parsed_board)

    winners =
      (column_winners ++ row_winners ++ diagonal_winners)
      |> Enum.filter(& &1)
      |> Enum.uniq()

    cond do
      winners == [] && full_board? ->
        {:ok, :draw}

      winners == [] ->
        {:ok, :ongoing}

      length(winners) == 1 ->
        {:ok, :win}

      length(winners) == 2 ->
        symbol = find_who_should_have_won(parsed_board)
        {:error, "Impossible board: game should have ended after #{symbol} won"}
    end
  end

  defp row_winners(parsed_board) do
    parsed_board
    |> Enum.map(&winner(&1))
  end

  defp column_winners(parsed_board) do
    parsed_board
    |> Enum.zip()
    |> Enum.map(&winner(Tuple.to_list(&1)))
  end

  defp diagonal_winners(parsed_board) do
    down_right =
      parsed_board
      |> Enum.with_index()
      |> Enum.map(fn {_, i} -> Enum.at(Enum.at(parsed_board, i), i) end)

    up_right =
      parsed_board
      |> Enum.with_index()
      |> Enum.map(fn {_, i} -> Enum.at(Enum.at(parsed_board, length(parsed_board) - i - 1), i) end)

    [winner(down_right), winner(up_right)]
  end

  defp winner(list) do
    if length(Enum.uniq(list)) == 1, do: hd(list), else: nil
  end

  defp find_who_should_have_won(parsed_board) do
    frequencies = frequencies(parsed_board)

    # this is not technically true because it is impossible to say who should have won in certain cases
    # without knowing the actual play older, e.g.:
    #
    #   XXX
    #   OOO
    #   X..
    #
    # In this case, the winner depends on what was X's last move.
    # If it was in the first column bottom row, then X won first.
    # If it was in last column first row, then O won first.
    should_have_won =
      cond do
        frequencies.x <= frequencies.o -> :x
        frequencies.x > frequencies.o -> :o
      end

    reverted_symbol_map = Map.new(@symbol_map, fn {key, val} -> {val, key} end)
    reverted_symbol_map[should_have_won]
  end
end

@rows [[{0, 0}, {0, 1}, {0, 2}], [{1, 0}, {1, 1}, {1, 2}], [{2, 0}, {2, 1}, {2, 2}]]
@columns [[{0, 0}, {1, 0}, {2, 0}], [{0, 1}, {1, 1}, {2, 1}], [{0, 2}, {1, 2}, {2, 2}]]
@diagonals [[{0, 0}, {1, 1}, {2, 2}], [{0, 2}, {1, 1}, {2, 0}]]

@doc """
Determine the state a game of tic-tac-toe where X starts.
"""
@spec game_state(board :: String.t()) :: {:ok, :win | :ongoing | :draw} | {:error, String.t()}
def game_state(board) do
board =
for {line, row} <- board |> String.split("\n", trim: true) |> Enum.with_index(),
{player, col} <- line |> to_charlist() |> Enum.with_index(),
into: %{} do
{{row, col}, player}
end

x_count = Enum.count(board, fn {_, c} -> c == ?X end)
o_count = Enum.count(board, fn {_, c} -> c == ?O end)

x_wins = wins?(board, ?X)
o_wins = wins?(board, ?O)

cond do
x_count - o_count > 1 ->
{:error, "Wrong turn order: X went twice"}

o_count - x_count > 0 ->
{:error, "Wrong turn order: O started"}

x_wins and o_wins ->
{:error, "Impossible board: game should have ended after the game was won"}

x_wins or o_wins ->
{:ok, :win}

o_count == 4 ->
{:ok, :draw}

true ->
{:ok, :ongoing}
end
end

defp wins?(board, player) do
Enum.any?(
@rows ++ @columns ++ @diagonals,
fn cells -> Enum.all?(cells, fn cell -> board[cell] == player end) end
)
end
end
88 changes: 88 additions & 0 deletions exercises/practice/state-of-tic-tac-toe/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[fe8e9fa9-37af-4d7e-aa24-2f4b8517161a]
description = "Won games -> Finished game where X won via column victory"

[96c30df5-ae23-4cf6-bf09-5ef056dddea1]
description = "Won games -> Finished game where X won via column victory"

[0d7a4b0a-2afd-4a75-8389-5fb88ab05eda]
description = "Won games -> Finished game where X won via column victory"

[bd1007c0-ec5d-4c60-bb9f-1a4f22177d51]
description = "Won games -> Finished game where O won via column victory"

[c032f800-5735-4354-b1b9-46f14d4ee955]
description = "Won games -> Finished game where O won via column victory"

[662c8902-c94a-4c4c-9d9c-e8ca513db2b4]
description = "Won games -> Finished game where O won via column victory"

[2d62121f-7e3a-44a0-9032-0d73e3494941]
description = "Won games -> Finished game where X won via row victory"

[108a5e82-cc61-409f-aece-d7a18c1beceb]
description = "Won games -> Finished game where X won via row victory"

[a013c583-75f8-4ab2-8d68-57688ff04574]
description = "Won games -> Finished game where X won via row victory"

[2c08e7d7-7d00-487f-9442-e7398c8f1727]
description = "Won games -> Finished game where O won via row victory"

[bb1d6c62-3e3f-4d1a-9766-f8803c8ed70f]
description = "Won games -> Finished game where O won via row victory"

[6ef641e9-12ec-44f5-a21c-660ea93907af]
description = "Won games -> Finished game where O won via row victory"

[ab145b7b-26a7-426c-ab71-bf418cd07f81]
description = "Won games -> Finished game where X won via diagonal victory"

[7450caab-08f5-4f03-a74b-99b98c4b7a4b]
description = "Won games -> Finished game where X won via diagonal victory"

[c2a652ee-2f93-48aa-a710-a70cd2edce61]
description = "Won games -> Finished game where O won via diagonal victory"

[5b20ceea-494d-4f0c-a986-b99efc163bcf]
description = "Won games -> Finished game where O won via diagonal victory"

[035a49b9-dc35-47d3-9d7c-de197161b9d4]
description = "Won games -> Finished game where X won via a row and a column victory"

[e5dfdeb0-d2bf-4b5a-b307-e673f69d4a53]
description = "Won games -> Finished game where X won via two diagonal victories"

[b42ed767-194c-4364-b36e-efbfb3de8788]
description = "Drawn games -> Draw"

[227a76b2-0fef-4e16-a4bd-8f9d7e4c3b13]
description = "Drawn games -> Draw"

[4d93f15c-0c40-43d6-b966-418b040012a9]
description = "Ongoing games -> Ongoing game"

[c407ae32-4c44-4989-b124-2890cf531f19]
description = "Ongoing games -> Ongoing game"

[199b7a8d-e2b6-4526-a85e-78b416e7a8a9]
description = "Ongoing games -> Ongoing game"

[1670145b-1e3d-4269-a7eb-53cd327b302e]
description = "Invalid boards -> Invalid board"

[47c048e8-b404-4bcf-9e51-8acbb3253f3b]
description = "Invalid boards -> Invalid board"

[b1dc8b13-46c4-47db-a96d-aa90eedc4e8d]
description = "Invalid boards -> Invalid board"
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
defmodule StateOfTicTacToe do
@doc """
Determine the state a game of tic-tac-toe where X starts.
"""
@spec game_state(board :: String.t()) :: {:ok, :win | :ongoing | :draw} | {:error, String.t()}
def game_state(board) do
end
end
28 changes: 28 additions & 0 deletions exercises/practice/state-of-tic-tac-toe/mix.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
defmodule StateOfTicTacToe.MixProject do
use Mix.Project

def project do
[
app: :state_of_tic_tac_toe,
version: "0.1.0",
# elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end

# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end

# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end
Loading