From ed4d53979b921841cb768e2c012fcb125a7f4be7 Mon Sep 17 00:00:00 2001 From: mos Date: Wed, 13 Nov 2024 14:03:31 +0100 Subject: [PATCH] add rnd macro --- src/lib.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 853ed1c..6dc7bc7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -342,6 +342,12 @@ struct Agent { goal: Solution, } +macro_rules! rnd { + ($max: expr) => { + rand::random::() % $max + }; +} + impl Agent { const WIN_REWARD: f32 = 100000.0; const BOX_REWARD: f32 = 0.00021; @@ -354,7 +360,7 @@ impl Agent { &[Direction::U, Direction::D, Direction::L, Direction::R]; fn chromo() -> Direction { - Self::DIR_TABLE[rand::random::() % Self::DIR_TABLE.len()] + Self::DIR_TABLE[rnd!(Self::DIR_TABLE.len())] } fn with_dna(state: State, dna: Vec) -> Self { @@ -374,7 +380,7 @@ impl Agent { } fn cross(&mut self, seed: &Self, cr: usize) { - let ratio = (rand::random::() % cr) + 1; + let ratio = rnd!(cr) + 1; let len = self.dna.len(); self.dna[..len / ratio].copy_from_slice(&seed.dna[..len / ratio]); @@ -382,8 +388,7 @@ impl Agent { fn mutate(&mut self, max: usize) { let len = self.dna.len(); - let ni = rand::random::() % max; - let nd = rand::random::() % len; + let (ni, nd) = (rnd!(max), rnd!(len)); for x in 0..ni { self.dna[(nd + x) % len] = Agent::chromo();