From 6517caec7100e53f768e2c53da29ef96bc58cd73 Mon Sep 17 00:00:00 2001 From: Yotoko <44945530+vhgcuong@users.noreply.github.com> Date: Wed, 20 Sep 2023 13:53:11 +0700 Subject: [PATCH] Update minesweeper --- src/minesweeper.rs | 50 +++++++++++----------------------------------- 1 file changed, 12 insertions(+), 38 deletions(-) diff --git a/src/minesweeper.rs b/src/minesweeper.rs index 89fe831..5f1ae1b 100644 --- a/src/minesweeper.rs +++ b/src/minesweeper.rs @@ -1,26 +1,22 @@ pub fn annotate(minefield: &[&str]) -> Vec { - if minefield.is_empty() { - return Vec::new(); - } - - let cleaned_strs: Vec> = 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(' '); } @@ -31,25 +27,3 @@ pub fn annotate(minefield: &[&str]) -> Vec { result } - -fn count_mines(cleaned_strs: &Vec>, 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 -}