feat: add basic grid random generation

This commit is contained in:
Mohammed Amar-Bensaber 2024-12-07 18:57:12 +01:00
parent 07437890c9
commit 568fad35d7
Signed by: renken
GPG key ID: 1F2BB159B645E575
3 changed files with 113 additions and 1 deletions

1
src/gen.rs Normal file
View file

@ -0,0 +1 @@
mod basic;

110
src/gen/basic.rs Normal file
View file

@ -0,0 +1,110 @@
//! Basic grid generation given a height, width and a seed.
use crate::grid::Grid;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
/// Basic grid generator.
///
/// TODO: Make width and height integer type generic?
pub struct BasicGridGenerator {
width: u8,
height: u8,
seed: u64,
}
impl BasicGridGenerator {
pub fn new(width: u8, height: u8, seed: u64) -> Self {
Self {
width,
height,
seed,
}
}
pub fn generate(&self) -> Grid {
let mut rng = ChaCha8Rng::seed_from_u64(self.seed);
let cells: Vec<_> = (0..self.width)
.into_iter()
.map(|_| {
(0..self.height)
.into_iter()
.map(|_| rng.gen())
.collect::<Vec<_>>()
})
.collect();
Grid::with_cells(cells)
}
}
#[cfg(test)]
mod tests {
use crate::grid::{Cell, Grid};
use super::BasicGridGenerator;
#[test]
fn ensure_grid_5x5_0_is_reproducible() {
let gen = BasicGridGenerator::new(5, 5, 0);
let grid = gen.generate();
println!("grid {:#?}", grid);
let expected_grid = Grid::with_cells(vec![
vec![
Cell::Empty,
Cell::Filled,
Cell::Empty,
Cell::Filled,
Cell::Empty,
],
vec![
Cell::Filled,
Cell::Empty,
Cell::Empty,
Cell::Empty,
Cell::Filled,
],
vec![
Cell::Empty,
Cell::Empty,
Cell::Filled,
Cell::Filled,
Cell::Empty,
],
vec![
Cell::Filled,
Cell::Filled,
Cell::Filled,
Cell::Filled,
Cell::Empty,
],
vec![
Cell::Empty,
Cell::Empty,
Cell::Filled,
Cell::Empty,
Cell::Empty,
],
]);
assert_eq!(grid, expected_grid);
}
#[test]
fn grid_5x5_u64_max_hints() {
let gen = BasicGridGenerator::new(5, 5, u64::MAX);
let grid = gen.generate();
println!("grid {:#?}", grid);
let (r_hints, c_hints) = grid.hints();
assert_eq!(
r_hints,
[vec![4], vec![1, 1], vec![1, 1], vec![1, 2], vec![1, 2]]
);
assert_eq!(
c_hints,
[vec![1], vec![3, 1], vec![1, 1], vec![2, 2], vec![1, 1, 1]]
);
}
}

View file

@ -1 +1,2 @@
mod core; mod gen;
mod grid;