Skip to content

Commit

Permalink
Update minesweeper
Browse files Browse the repository at this point in the history
  • Loading branch information
vhgcuong committed Sep 20, 2023
1 parent 7aa27cf commit 6517cae
Showing 1 changed file with 12 additions and 38 deletions.
50 changes: 12 additions & 38 deletions src/minesweeper.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
pub fn annotate(minefield: &[&str]) -> Vec<String> {
if minefield.is_empty() {
return Vec::new();
}

let cleaned_strs: Vec<Vec<char>> = minefield
.iter()
.map(|x| x.chars().collect())
.collect();

let (x_len, y_len) = (cleaned_strs.len(), cleaned_strs[0].len());

let mut result = Vec::new();

for (x, row) in cleaned_strs.iter().enumerate() {
for (x, row) in minefield.iter().enumerate() {
let mut result_row = String::new();
for (y, item) in row.iter().enumerate() {
if *item == '*' {
for (y, item) in row.chars().enumerate() {
if item == '*' {
result_row.push('*');
} else {
let count = count_mines(&cleaned_strs, x as isize, y as isize, x_len as isize, y_len as isize);
let mut count = 0;
for i in x.saturating_sub(1)..=(x + 1) {
for j in y.saturating_sub(1)..=(y + 1) {
if i < minefield.len() && j < row.len() && minefield[i].chars().nth(j) == Some('*') {
count += 1;
}
}
}
if count > 0 {
result_row.push(char::from_digit(count as u32, 10).unwrap());
result_row.push_str(&count.to_string());
} else {
result_row.push(' ');
}
Expand All @@ -31,25 +27,3 @@ pub fn annotate(minefield: &[&str]) -> Vec<String> {

result
}

fn count_mines(cleaned_strs: &Vec<Vec<char>>, x: isize, y: isize, x_len: isize, y_len: isize) -> u8 {
let mut count: u8 = 0;

for dx in -1..=1 {
for dy in -1..=1 {
if dx == 0 && dy == 0 {
continue;
}
let new_x = x + dx;
let new_y = y + dy;

if new_x >= 0 && new_x < x_len && new_y >= 0 && new_y < y_len {
if cleaned_strs[new_x as usize][new_y as usize] == '*' {
count += 1;
}
}
}
}

count
}

0 comments on commit 6517cae

Please sign in to comment.