Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- mod minesweeper {
- use std;
- pub fn is_mine(string: &str, x_pos: usize) -> bool {
- string.chars().nth(x_pos).unwrap() == '*'
- }
- pub fn fill(empty: Vec<&str>) -> Vec<std::string::String> {
- let mut result = vec![];
- for (y_pos, row) in empty.iter().enumerate() {
- let mut new_row = String::from(empty[y_pos]);
- for (x_pos, c) in row.chars().enumerate() {
- let b_up: bool = y_pos > 0;
- let b_down: bool = empty.len() > y_pos + 1;
- let b_left: bool = x_pos > 0;
- let b_right: bool = row.len() > x_pos + 1;
- let mine_count = [
- // looking up
- b_up && is_mine(empty[y_pos - 1], x_pos),
- // looking down
- b_down && is_mine(empty[y_pos + 1], x_pos),
- // looking left
- b_left && is_mine(empty[y_pos], x_pos - 1),
- // looking right
- b_right && is_mine(empty[y_pos], x_pos + 1),
- // looking up left
- b_up && b_left && is_mine(empty[y_pos - 1], x_pos - 1),
- // looking up right
- b_up && b_right && is_mine(empty[y_pos - 1], x_pos + 1),
- // looking down left
- b_down && b_left && is_mine(empty[y_pos + 1], x_pos - 1),
- // looking down right
- b_down && b_right && is_mine(empty[y_pos + 1], x_pos + 1)
- ].iter().filter(|x| **x ).count();
- if c == ' ' && mine_count > 0 {
- new_row.remove(x_pos);
- new_row.insert(x_pos, mine_count.to_string()
- .chars()
- .next()
- .unwrap());
- }
- }
- result.push(new_row);
- };
- result
- }
- }
- #[test]
- fn add_numbers_to_empty_sweeper_board() {
- assert_eq!(
- minesweeper::fill(vec![
- " ",
- " ",
- " "
- ]),
- vec![
- " ",
- " ",
- " "
- ]
- )
- }
- #[test]
- fn add_numbers_to_filled_sweeper_board() {
- assert_eq!(
- minesweeper::fill(vec![
- "** ",
- " ",
- " "
- ]),
- vec![
- "**1",
- "221",
- " "
- ]
- )
- }
- #[test]
- fn add_numbers_to_all_mines() {
- assert_eq!(
- minesweeper::fill(vec![
- "***",
- "* *",
- "***"
- ]),
- vec![
- "***",
- "*8*",
- "***"
- ]
- )
- }
- #[test]
- fn add_numbers_to_bigger_filled_sweeper_board() {
- assert_eq!(
- minesweeper::fill(vec![
- "** ",
- " ",
- " * ",
- " "
- ]),
- vec![
- "**1 ",
- "2321",
- " 1*1",
- " 111"
- ]
- )
- }
Add Comment
Please, Sign In to add comment