Avatar of davearonson

davearonson's solution

to Minesweeper in the Elixir Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Add the numbers to a minesweeper board.

Minesweeper is a popular game where the user has to find the mines using numeric hints that indicate how many mines are directly adjacent (horizontally, vertically, diagonally) to a square.

In this exercise you have to create some code that counts the number of mines adjacent to a square and transforms boards like this (where * indicates a mine):

+-----+
| * * |
|  *  |
|  *  |
|     |
+-----+

into this:

+-----+
|1*3*1|
|13*31|
| 2*2 |
| 111 |
+-----+

Running tests

Execute the tests with:

$ elixir minesweeper_test.exs

Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by commenting out the relevant @tag :pending with a # symbol.

For example:

# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end

Or, you can enable all the tests by commenting out the ExUnit.configure line in the test suite.

# ExUnit.configure exclude: :pending, trace: true

For more detailed information about the Elixir track, please see the help page.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

minesweeper_test.exs

if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("minesweeper.exs", __DIR__)
end

ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)

defmodule MinesweeperTest do
  use ExUnit.Case

  defp clean(b), do: Enum.map(b, &String.replace(&1, ~r/[^*]/, " "))

  # @tag :pending
  test "zero size board" do
    b = []
    assert Minesweeper.annotate(clean(b)) == b
  end

  @tag :pending
  test "empty board" do
    b = ["   ", "   ", "   "]
    assert Minesweeper.annotate(clean(b)) == b
  end

  @tag :pending
  test "board full of mines" do
    b = ["***", "***", "***"]
    assert Minesweeper.annotate(clean(b)) == b
  end

  @tag :pending
  test "surrounded" do
    b = ["***", "*8*", "***"]
    assert Minesweeper.annotate(clean(b)) == b
  end

  @tag :pending
  test "horizontal line" do
    b = ["1*2*1"]
    assert Minesweeper.annotate(clean(b)) == b
  end

  @tag :pending
  test "vertical line" do
    b = ["1", "*", "2", "*", "1"]
    assert Minesweeper.annotate(clean(b)) == b
  end

  @tag :pending
  test "cross" do
    b = [" 2*2 ", "25*52", "*****", "25*52", " 2*2 "]
    assert Minesweeper.annotate(clean(b)) == b
  end
end
defmodule Minesweeper do

  @doc """
  Annotate empty spots next to mines with the number of mines next to them.
  """
  @spec annotate([String.t]) :: [String.t]

  def annotate(board) do
    # make it a *tuple of rows*, with each a tuple of cells
    # for each row, for each cell, if it's blank,
    # set it to how many neighbors are mines if any.
    tuple_version = board
                    |> Enum.map(&tupleize_string/1)
                    |> List.to_tuple
    board
    |> Enum.with_index
    |> Enum.map(&(annotate_row(&1, tuple_version)))
  end

  defp tupleize_string(str) do
    str |> String.graphemes |> List.to_tuple
  end

  defp annotate_row({row, row_num}, board) do
    row
    |> String.graphemes
    |> Enum.with_index
    |> Enum.map(&(annotate_cell(&1, row_num, board)))
    |> Enum.join
  end

  defp annotate_cell({"*", col_num}, _row_num, _board), do: "*"
  defp annotate_cell({val, col_num},  row_num,  board)  do
    count_neighbors(row_num, col_num, board)
    |> (fn(x) -> if x == 0, do: " ", else: x end).()
  end

  defp count_neighbors(row_num, col_num, board) do
    (-1..1)
    |> Enum.map(&(count_neighbors_in_row(row_num, &1, col_num, board)))
    |> Enum.reduce(&+/2)
  end

  defp count_neighbors_in_row(row_num, row_delta, _col_num, board)
       when row_num + row_delta < 0
         or row_num + row_delta >= tuple_size(board), do: 0
  defp count_neighbors_in_row(row_num, row_delta, col_num, board) do
    (-1..1)
    |> Enum.map(&(check_neighbors_at(row_delta,
                                     col_num, &1,
                                     elem(board, row_num + row_delta))))
    |> Enum.reduce(&+/2)
  end

  defp check_neighbors_at(0,          _col_num, 0,         _row), do: 0
  defp check_neighbors_at(_row_delta,  col_num, col_delta,  row)
       when col_num + col_delta < 0
         or col_num + col_delta >= tuple_size(row), do: 0
  defp check_neighbors_at(_row_delta, col_num, col_delta, row) do
    row
    |> elem(col_num + col_delta)
    |> (fn(x) -> if x == "*", do: 1, else: 0 end).()
  end
end

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?