add rnd macro

This commit is contained in:
mos 2024-11-13 14:03:31 +01:00
parent 79357432d7
commit ed4d53979b
1 changed files with 9 additions and 4 deletions

View File

@ -342,6 +342,12 @@ struct Agent {
goal: Solution,
}
macro_rules! rnd {
($max: expr) => {
rand::random::<usize>() % $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::<usize>() % Self::DIR_TABLE.len()]
Self::DIR_TABLE[rnd!(Self::DIR_TABLE.len())]
}
fn with_dna(state: State, dna: Vec<Direction>) -> Self {
@ -374,7 +380,7 @@ impl Agent {
}
fn cross(&mut self, seed: &Self, cr: usize) {
let ratio = (rand::random::<usize>() % 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::<usize>() % max;
let nd = rand::random::<usize>() % len;
let (ni, nd) = (rnd!(max), rnd!(len));
for x in 0..ni {
self.dna[(nd + x) % len] = Agent::chromo();