use alloc::{collections::BTreeMap, vec::Vec};
#[derive(Debug, Clone)]
pub(super) struct Cell<const K: usize> {
pub(super) motions: Vec<usize>,
pub(super) coverage: f64,
pub(super) selections: f64,
pub(super) score: f64,
pub(super) iteration: usize,
pub(super) neighbors: usize,
}
impl<const K: usize> Cell<K> {
pub(super) fn importance(&self) -> f64 {
let neighbors = f64::from(u32::try_from(self.neighbors).unwrap_or(u32::MAX));
self.score / ((neighbors + 1.0) * self.coverage * self.selections)
}
pub(super) const fn is_interior(&self) -> bool {
self.neighbors >= 2 * K
}
}
#[derive(Debug, Clone)]
pub(super) struct Grid<const K: usize> {
pub(super) cells: Vec<Cell<K>>,
index: BTreeMap<[i64; K], usize>,
}
impl<const K: usize> Grid<K> {
pub(super) const fn new() -> Self {
Self {
cells: Vec::new(),
index: BTreeMap::new(),
}
}
pub(super) fn find(&self, coord: &[i64; K]) -> Option<usize> {
self.index.get(coord).copied()
}
pub(super) fn add(&mut self, coord: [i64; K], iteration: usize, score: f64) -> usize {
let id = self.cells.len();
let mut neighbors = 0;
for neighbor in axis_neighbors(&coord) {
if let Some(other) = self.find(&neighbor) {
self.cells[other].neighbors += 1;
neighbors += 1;
}
}
self.cells.push(Cell {
motions: Vec::new(),
coverage: 0.0,
selections: 1.0,
score,
iteration,
neighbors,
});
self.index.insert(coord, id);
id
}
pub(super) fn exterior_fraction(&self) -> f64 {
let exterior = self.cells.iter().filter(|cell| !cell.is_interior()).count();
let to_f64 = |n: usize| f64::from(u32::try_from(n).unwrap_or(u32::MAX));
if self.cells.is_empty() {
0.0
} else {
to_f64(exterior) / to_f64(self.cells.len())
}
}
pub(super) fn select(&self, exterior: bool) -> Option<usize> {
self.best_of(|cell| cell.is_interior() != exterior)
.or_else(|| self.best_of(|_| true))
}
fn best_of(&self, filter: impl Fn(&Cell<K>) -> bool) -> Option<usize> {
let mut best: Option<(usize, f64)> = None;
for (id, cell) in self
.cells
.iter()
.enumerate()
.filter(|(_, cell)| filter(cell))
{
let importance = cell.importance();
if best.is_none_or(|(_, top)| importance > top) {
best = Some((id, importance));
}
}
best.map(|(id, _)| id)
}
pub(super) fn refresh_scores(&mut self) {
for cell in &mut self.cells {
cell.score +=
1.0 + libm::log(f64::from(u32::try_from(cell.iteration).unwrap_or(u32::MAX)));
}
}
}
fn axis_neighbors<const K: usize>(coord: &[i64; K]) -> impl Iterator<Item = [i64; K]> + '_ {
(0..K).flat_map(move |axis| {
[-1, 1].into_iter().map(move |delta| {
let mut neighbor = *coord;
neighbor[axis] = neighbor[axis].saturating_add(delta);
neighbor
})
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn neighbor_counts_track_both_sides_and_interior_cells() {
let mut grid = Grid::<2>::new();
let center = grid.add([0, 0], 1, 1.0);
for coord in [[1, 0], [-1, 0], [0, 1]] {
grid.add(coord, 1, 1.0);
}
assert_eq!(grid.cells[center].neighbors, 3);
assert!(!grid.cells[center].is_interior());
grid.add([0, -1], 1, 1.0);
assert!(grid.cells[center].is_interior());
assert_eq!(grid.cells[grid.find(&[1, 0]).expect("added")].neighbors, 1);
assert!((grid.exterior_fraction() - 0.8).abs() < 1e-12);
}
#[test]
fn selection_prefers_the_class_and_the_importance() {
let mut grid = Grid::<1>::new();
let left = grid.add([0], 1, 1.0);
let right = grid.add([1], 1, 4.0);
grid.add([2], 1, 1.0);
for cell in &mut grid.cells {
cell.coverage = 1.0;
}
assert_eq!(grid.select(false), Some(right));
assert_eq!(
grid.select(true),
Some(left),
"oldest exterior cell on ties"
);
}
}