Solve minesweeper

This commit is contained in:
Avery Winters 2023-12-14 19:30:01 -06:00
parent a5cc68b6b3
commit 1dad709dd5
Signed by: avery
SSH key fingerprint: SHA256:eesvLB5MMqHLZrAMFt6kEhqJWnASMLcET6Sgmw0FqZI
8 changed files with 408 additions and 0 deletions

View file

@ -0,0 +1,38 @@
{
"authors": [
"EduardoBautista"
],
"contributors": [
"ashleygwilliams",
"coriolinus",
"cwhakes",
"EduardoBautista",
"efx",
"ErikSchierboom",
"ffflorian",
"IanWhitney",
"kytrinyx",
"lutostag",
"mkantor",
"nfiles",
"petertseng",
"rofrol",
"stringparser",
"workingjubilee",
"xakon",
"ZapAnton"
],
"files": {
"solution": [
"src/lib.rs",
"Cargo.toml"
],
"test": [
"tests/minesweeper.rs"
],
"example": [
".meta/example.rs"
]
},
"blurb": "Add the numbers to a minesweeper board."
}

View file

@ -0,0 +1 @@
{"track":"rust","exercise":"minesweeper","id":"8ae8e96f4272474ba9959d1289415da1","url":"https://exercism.org/tracks/rust/exercises/minesweeper","handle":"averywinters","is_requester":true,"auto_approve":false}

8
rust/minesweeper/.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
# Generated by Cargo
# will have compiled files and executables
/target/
**/*.rs.bk
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
Cargo.lock

View file

@ -0,0 +1,4 @@
[package]
edition = "2021"
name = "minesweeper"
version = "1.1.0"

86
rust/minesweeper/HELP.md Normal file
View file

@ -0,0 +1,86 @@
# Help
## Running the tests
Execute the tests with:
```bash
$ 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 _only ignored_ tests without editing the tests source file, use:
```bash
$ cargo test -- --ignored
```
If you are using Rust 1.51 or later, you can run _all_ tests with
```bash
$ cargo test -- --include-ignored
```
To run a specific test, for example `some_test`, you can use:
```bash
$ cargo test some_test
```
If the specific test is ignored, use:
```bash
$ cargo test some_test -- --ignored
```
To learn more about Rust tests refer to the online [test documentation][rust-tests].
[rust-tests]: https://doc.rust-lang.org/book/ch11-02-running-tests.html
## Submitting your solution
You can submit your solution using the `exercism submit src/lib.rs Cargo.toml` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [Rust track's documentation](https://exercism.org/docs/tracks/rust)
- The [Rust track's programming category on the forum](https://forum.exercism.org/c/programming/rust)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
## Rust Installation
Refer to the [exercism help page][help-page] for Rust installation and learning
resources.
## 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 GitHub [track repository][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.
[help-page]: https://exercism.org/tracks/rust/learning
[github]: https://github.com/exercism/rust
[contribution guide]: https://exercism.org/docs/community/contributors

View file

@ -0,0 +1,73 @@
# Minesweeper
Welcome to Minesweeper on Exercism's Rust Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Add the mine counts to a completed 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 given empty square and replaces that square with the count.
The board is a rectangle composed of blank space (' ') characters.
A mine is represented by an asterisk (`*`) character.
If a given space has no adjacent mines at all, leave that square blank.
## Examples
For example you may receive a 5 x 4 board like this (empty spaces are represented here with the '·' character for display on screen):
```text
·*·*·
··*··
··*··
·····
```
And your code will transform it into this:
```text
1*3*1
13*31
·2*2·
·111·
```
## Performance Hint
All the inputs and outputs are in ASCII.
Rust `String`s and `&str` are utf8, so while one might expect `"Hello".chars()` to be simple, it actually has to check each char to see if it's 1, 2, 3 or 4 `u8`s long.
If we know a `&str` is ASCII then we can call `.as_bytes()` and refer to the underlying data as a `&[u8]` (byte slice).
Iterating over a slice of ASCII bytes is much quicker as there are no codepoints involved - every ASCII byte is one `u8` long.
Can you complete the challenge without cloning the input?
## Source
### Created by
- @EduardoBautista
### Contributed to by
- @ashleygwilliams
- @coriolinus
- @cwhakes
- @EduardoBautista
- @efx
- @ErikSchierboom
- @ffflorian
- @IanWhitney
- @kytrinyx
- @lutostag
- @mkantor
- @nfiles
- @petertseng
- @rofrol
- @stringparser
- @workingjubilee
- @xakon
- @ZapAnton

View file

@ -0,0 +1,57 @@
pub fn annotate(minefield: &[&str]) -> Vec<String> {
minefield
.iter()
.enumerate()
.map(|(row_index, row)| annotate_row(row_index, row.as_bytes(), minefield))
.collect()
}
fn annotate_row(row_index: usize, row: &[u8], minefield: &[&str]) -> String {
row.iter()
.enumerate()
.map(|(column_index, &ch)| annotate_cell(row_index, column_index, ch, minefield))
.collect()
}
fn annotate_cell(row_index: usize, column_index: usize, ch: u8, minefield: &[&str]) -> char {
let mine_count = adjacent_mine_count(row_index, column_index, minefield);
let count_ch = char::from_digit(mine_count as u32, 10)
.expect("Number of adjacent cells was higher than expected.");
if !is_mine(ch) && mine_count != 0 {
count_ch
} else {
ch as char
}
}
fn adjacent_mine_count(row_index: usize, column_index: usize, minefield: &[&str]) -> usize {
const ADJACENT_OFFSETS: &[(isize, isize)] = &[
(-1, -1),
(-1, 0),
(-1, 1),
(0, -1),
(0, 1),
(1, -1),
(1, 0),
(1, 1),
];
let adjacent_cell = |row_offset, column_offset| {
let adjacent_row = row_index
.checked_add_signed(row_offset)
.and_then(|row_index| minefield.get(row_index))?
.as_bytes();
let adjacent_ch = column_index
.checked_add_signed(column_offset)
.and_then(|column_index| adjacent_row.get(column_index))?;
Some(*adjacent_ch)
};
ADJACENT_OFFSETS
.iter()
.filter_map(|&(row_offset, column_offset)| adjacent_cell(row_offset, column_offset))
.filter(|&ch| is_mine(ch))
.count()
}
const fn is_mine(ch: u8) -> bool {
ch == b'*'
}

View file

@ -0,0 +1,141 @@
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() {
#[rustfmt::skip]
run_test(&[
]);
}
#[test]
fn no_columns() {
#[rustfmt::skip]
run_test(&[
"",
]);
}
#[test]
fn no_mines() {
#[rustfmt::skip]
run_test(&[
" ",
" ",
" ",
]);
}
#[test]
fn board_with_only_mines() {
#[rustfmt::skip]
run_test(&[
"***",
"***",
"***",
]);
}
#[test]
fn mine_surrounded_by_spaces() {
#[rustfmt::skip]
run_test(&[
"111",
"1*1",
"111",
]);
}
#[test]
fn space_surrounded_by_mines() {
#[rustfmt::skip]
run_test(&[
"***",
"*8*",
"***",
]);
}
#[test]
fn horizontal_line() {
#[rustfmt::skip]
run_test(&[
"1*2*1",
]);
}
#[test]
fn horizontal_line_mines_at_edges() {
#[rustfmt::skip]
run_test(&[
"*1 1*",
]);
}
#[test]
fn vertical_line() {
#[rustfmt::skip]
run_test(&[
"1",
"*",
"2",
"*",
"1",
]);
}
#[test]
fn vertical_line_mines_at_edges() {
#[rustfmt::skip]
run_test(&[
"*",
"1",
" ",
"1",
"*",
]);
}
#[test]
fn cross() {
#[rustfmt::skip]
run_test(&[
" 2*2 ",
"25*52",
"*****",
"25*52",
" 2*2 ",
]);
}
#[test]
fn large_board() {
#[rustfmt::skip]
run_test(&[
"1*22*1",
"12*322",
" 123*2",
"112*4*",
"1*22*2",
"111111",
]);
}