From a1373ec338658e0c4fe1c7add88d781fb3c919d4 Mon Sep 17 00:00:00 2001 From: Simon Gardling Date: Mon, 27 Jan 2025 14:30:41 -0500 Subject: [PATCH] improve prop range splitting --- src/main.rs | 1 + src/misc.rs | 24 ++++++++++++++++++++++++ src/repr.rs | 29 +++++++++++++---------------- 3 files changed, 38 insertions(+), 16 deletions(-) create mode 100644 src/misc.rs diff --git a/src/main.rs b/src/main.rs index 10ab0fd..9a94f1c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,7 @@ use repr::{Board, Piece}; mod agent; mod game; +mod misc; mod repr; fn main() { diff --git a/src/misc.rs b/src/misc.rs new file mode 100644 index 0000000..1ffb2d5 --- /dev/null +++ b/src/misc.rs @@ -0,0 +1,24 @@ +pub fn split(min: usize, max: usize, x: usize) -> Vec> { + if min > x || x > max { + return Vec::new(); + } + let index = x - min; + + let collected = (min..=max).collect::>(); + let split = collected.split_at(index); + let mut one = split.0.to_vec(); + one.reverse(); + let mut two = split.1.to_vec(); + two.remove(0); + vec![one, two] +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn split_test() { + assert_eq!(split(0, 6, 2), vec![vec![1, 0], vec![3, 4, 5, 6]]); + } +} diff --git a/src/repr.rs b/src/repr.rs index 9a2dd1a..326bd05 100644 --- a/src/repr.rs +++ b/src/repr.rs @@ -1,5 +1,7 @@ use std::fmt; +use crate::misc::split; + #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum Piece { Black, @@ -76,55 +78,50 @@ impl Board { return; }; - // both ranges expand __from__ the piece - let i_ranges: Vec> = - vec![(0..i).rev().collect(), ((i + 1)..BOARD_SIZE).collect()]; - let j_ranges: Vec> = - vec![(0..j).rev().collect(), ((j + 1)..BOARD_SIZE).collect()]; - - for i_range in i_ranges { + for range in split(0, BOARD_SIZE - 1, i) { let mut chain_length: usize = 0; - for &new_i in &i_range { + for &new_i in &range { let Some(piece) = self.get(new_i, j) else { break; }; if piece == &starting_color { if chain_length > 0 { // fill all opposite colors with this color - let Some(i_o_s) = i_range.get(..chain_length) else { + let Some(i_o_s) = range.get(..chain_length) else { break; }; + + // fill all opposite colors with this color for i_o in i_o_s { self.place_and_prop_unchecked(*i_o, j, starting_color); } } break; - } else { - chain_length += 1; } + chain_length += 1; } } - for j_range in j_ranges { + for range in split(0, BOARD_SIZE - 1, j) { let mut chain_length: usize = 0; - for &new_j in &j_range { + for &new_j in &range { let Some(piece) = self.get(i, new_j) else { break; }; if piece == &starting_color { if chain_length > 0 { - let Some(j_o_s) = j_range.get(..chain_length) else { + let Some(j_o_s) = range.get(..chain_length) else { break; }; + // fill all opposite colors with this color for j_o in j_o_s { self.place_and_prop_unchecked(i, *j_o, starting_color); } } break; - } else { - chain_length += 1; } + chain_length += 1; } } }