flowers field improved

This commit is contained in:
Rorik Star Platinum 2025-12-07 20:33:47 +03:00
parent 99212eb167
commit ffe7f7c9af
2 changed files with 78 additions and 44 deletions

View file

@ -1,30 +1,22 @@
pub enum Cell {
Some(u32),
Flower,
None,
}
pub trait NeighbourCounter { pub trait NeighbourCounter {
fn count_neighbours(&self, x: usize, y: usize) -> u8; fn place_cell(&self, x: usize, y: usize) -> char;
} }
impl NeighbourCounter for [&str] { impl NeighbourCounter for [&str] {
fn count_neighbours(&self, y: usize, x: usize) -> u8 { fn place_cell(&self, x: usize, y: usize) -> char {
if 0 == self.len() { if b'*' == self[y].as_bytes()[x] {
return 0; return '*';
};
let count = (y.saturating_sub(1)..=(y + 1).min(self.len() - 1))
.flat_map(|ny| {
(x.saturating_sub(1)..=(x + 1).min(self[0].len() - 1)).map(move |nx| (ny, nx))
})
.filter(|&(ny, nx)| b'*' == self[ny].as_bytes()[nx])
.count();
match count {
0 => ' ',
c => (b'0' + c as u8) as char,
} }
let mut count = 0;
for i in y.saturating_sub(1)..=(y + 1).min(self.len() - 1) {
for j in x.saturating_sub(1)..=(x + 1).min(self[0].len() - 1) {
if i == y && j == x {
continue;
}
if b'*' == self[i].as_bytes()[j] {
count += 1;
}
}
}
count
} }
} }
@ -32,28 +24,11 @@ pub fn annotate(garden: &[&str]) -> Vec<String> {
if 0 == garden.len() { if 0 == garden.len() {
return vec![]; return vec![];
} }
garden (0..garden.len())
.iter() .map(|y| {
.enumerate() (0..garden[y].len())
.map(|(i, line)| { .map(|x| garden.place_cell(x, y))
let new_line: String = line .collect()
.as_bytes()
.iter()
.enumerate()
.map(|(j, &byte)| {
if b'*' == byte {
return '*';
}
let count = garden.count_neighbours(i, j);
match count {
0 => ' ',
c => (b'0' + c) as char,
}
})
.collect();
new_line
}) })
.collect() .collect()
} }

View file

@ -0,0 +1,59 @@
pub enum Cell {
Some(u32),
Flower,
None,
}
pub trait NeighbourCounter {
fn count_neighbours(&self, x: usize, y: usize) -> u8;
}
impl NeighbourCounter for [&str] {
fn count_neighbours(&self, y: usize, x: usize) -> u8 {
if 0 == self.len() {
return 0;
}
let mut count = 0;
for i in y.saturating_sub(1)..=(y + 1).min(self.len() - 1) {
for j in x.saturating_sub(1)..=(x + 1).min(self[0].len() - 1) {
if i == y && j == x {
continue;
}
if b'*' == self[i].as_bytes()[j] {
count += 1;
}
}
}
count
}
}
pub fn annotate(garden: &[&str]) -> Vec<String> {
if 0 == garden.len() {
return vec![];
}
garden
.iter()
.enumerate()
.map(|(i, line)| {
let new_line: String = line
.as_bytes()
.iter()
.enumerate()
.map(|(j, &byte)| {
if b'*' == byte {
return '*';
}
let count = garden.count_neighbours(i, j);
match count {
0 => ' ',
c => (b'0' + c) as char,
}
})
.collect();
new_line
})
.collect()
}