🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of bkhl

bkhl's solution

to Minesweeper in the Rust Track

Published at Oct 31 2020 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution 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 |
+-----+

Rust Installation

Refer to the exercism help page for Rust installation and learning resources.

Writing the Code

Execute the tests with:

$ cargo test

All but the first test have been ignored. After you get the first test to pass, open the tests source file which is located in the tests directory and remove the #[ignore] flag from the next test and get the tests to pass again. Each separate test is a function with #[test] flag above it. Continue, until you pass every test.

If you wish to run all tests without editing the tests source file, use:

$ cargo test -- --ignored

To run a specific test, for example some_test, you can use:

$ cargo test some_test

If the specific test is ignored use:

$ cargo test some_test -- --ignored

To learn more about Rust tests refer to the online test documentation

Make sure to read the Modules chapter if you haven't already, it will help you with organizing your files.

Further improvements

After you have solved the exercise, please consider using the additional utilities, described in the installation guide, to further refine your final solution.

To format your solution, inside the solution directory use

cargo fmt

To see, if your solution contains some common ineffective use cases, inside the solution directory use

cargo clippy --all-targets

Submitting the solution

Generally you should submit all files in which you implemented your solution (src/lib.rs in most cases). If you are using any external crates, please consider submitting the Cargo.toml file. This will make the review process faster and clearer.

Feedback, Issues, Pull Requests

The exercism/rust repository on GitHub is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help!

If you want to know more about Exercism, take a look at the contribution guide.

Submitting Incomplete Solutions

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

minesweeper.rs

use minesweeper::annotate;

fn remove_annotations(board: &[&str]) -> Vec<String> {
    board.iter().map(|r| remove_annotations_in_row(r)).collect()
}

fn remove_annotations_in_row(row: &str) -> String {
    row.chars().map(|ch| match ch {
        '*' => '*',
        _ => ' '
    }).collect()
}

fn run_test(test_case: &[&str]) {
    let cleaned = remove_annotations(test_case);
    let cleaned_strs = cleaned.iter().map(|r| &r[..]).collect::<Vec<_>>();
    let expected = test_case.iter().map(|&r| r.to_string()).collect::<Vec<_>>();
    assert_eq!(expected, annotate(&cleaned_strs));
}

#[test]
fn no_rows() {
    run_test(&[
    ]);
}

#[test]
#[ignore]
fn no_columns() {
    run_test(&[
        "",
    ]);
}

#[test]
#[ignore]
fn no_mines() {
    run_test(&[
        "   ",
        "   ",
        "   ",
    ]);
}

#[test]
#[ignore]
fn board_with_only_mines() {
    run_test(&[
        "***",
        "***",
        "***",
    ]);
}

#[test]
#[ignore]
fn mine_surrounded_by_spaces() {
    run_test(&[
        "111",
        "1*1",
        "111",
    ]);
}

#[test]
#[ignore]
fn space_surrounded_by_mines() {
    run_test(&[
        "***",
        "*8*",
        "***",
    ]);
}

#[test]
#[ignore]
fn horizontal_line() {
    run_test(&[
        "1*2*1",
    ]);
}

#[test]
#[ignore]
fn horizontal_line_mines_at_edges() {
    run_test(&[
        "*1 1*",
    ]);
}

#[test]
#[ignore]
fn vertical_line() {
    run_test(&[
        "1",
        "*",
        "2",
        "*",
        "1",
    ]);
}

#[test]
#[ignore]
fn vertical_line_mines_at_edges() {
    run_test(&[
        "*",
        "1",
        " ",
        "1",
        "*",
    ]);
}

#[test]
#[ignore]
fn cross() {
    run_test(&[
        " 2*2 ",
        "25*52",
        "*****",
        "25*52",
        " 2*2 ",
    ]);
}

#[test]
#[ignore]
fn large_board() {
    run_test(&[
        "1*22*1",
        "12*322",
        " 123*2",
        "112*4*",
        "1*22*2",
        "111111",
    ]);
}
use std::char::from_digit;

/// Given an array of string slices representing a Minesweeper map, return a
/// vector of strings, with the mines marked out, and empty squares marked with
/// a digit indicating the number of adjacent mines.
pub fn annotate(minefield: &[&str]) -> Vec<String> {
    (0..minefield.len())
        .map(|y| {
            (0..minefield[y].len())
                .map(|x| annotate_square(x, y, minefield))
                .collect()
        })
        .collect()
}

// Get the annotation for a square with the given coordinates.
fn annotate_square(x: usize, y: usize, minefield: &[&str]) -> char {
    match &minefield[y].chars().nth(x).unwrap() {
        '*' => '*',
        ' ' => match count_adjacent_mines(x, y, minefield) {
            0 => ' ',
            n => from_digit(n as u32, 10).unwrap(),
        },
        _ => panic!(),
    }
}

// Count the number of adjacent mines for a square with the given coordinates.
fn count_adjacent_mines(x: usize, y: usize, minefield: &[&str]) -> usize {
    minefield
        .iter()
        .skip(if y == 0 { 0 } else { y - 1 })
        .take(if y == 0 { 2 } else { 3 })
        .map(|row| {
            row.chars()
                .skip(if x == 0 { 0 } else { x - 1 })
                .take(if x == 0 { 2 } else { 3 })
                .filter(|c| *c == '*')
                .count()
        })
        .sum()
}

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?