From 5bc21c459d6d04c895886b3051e90d23b7ed22b7 Mon Sep 17 00:00:00 2001 From: Edward Shen Date: Thu, 16 Apr 2020 12:54:11 -0400 Subject: [PATCH] add more features to genetic algorithm --- src/actors/genetic.rs | 46 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/src/actors/genetic.rs b/src/actors/genetic.rs index cf23488..4e81c30 100644 --- a/src/actors/genetic.rs +++ b/src/actors/genetic.rs @@ -17,6 +17,8 @@ pub struct Parameters { bumpiness: f64, holes: f64, complete_lines: f64, + max_height: f64, + max_well_depth: f64, } impl Default for Parameters { @@ -26,6 +28,8 @@ impl Default for Parameters { bumpiness: 1.0, holes: 1.0, complete_lines: 1.0, + max_height: 1.0, + max_well_depth: 1.0, } } } @@ -33,11 +37,13 @@ impl Default for Parameters { impl Parameters { fn mutate(mut self, rng: &mut SmallRng) { let mutation_amt = rng.gen_range(-0.2, 0.2); - match rng.gen_range(0, 4) { + match rng.gen_range(0, 6) { 0 => self.total_height += mutation_amt, 1 => self.bumpiness += mutation_amt, 2 => self.holes += mutation_amt, 3 => self.complete_lines += mutation_amt, + 4 => self.max_height += mutation_amt, + 5 => self.max_well_depth += mutation_amt, _ => unreachable!(), } @@ -45,7 +51,8 @@ impl Parameters { + self.bumpiness.powi(2) + self.holes.powi(2) + self.complete_lines.powi(2)) - .sqrt(); + + self.max_height.powi(2) + + self.max_well_depth.powi(2).sqrt(); self.total_height /= normalization_factor; self.bumpiness /= normalization_factor; @@ -75,6 +82,8 @@ impl Default for GeneticHeuristicAgent { bumpiness: rng.gen::(), holes: rng.gen::(), complete_lines: rng.gen::(), + max_height: rng.gen::(), + max_well_depth: rng.gen::(), }, } } @@ -118,11 +127,40 @@ impl GeneticHeuristicAgent { } } + let max_height = heights.iter().max().unwrap().unwrap_or_else(|| 0) as f64; + + let mut max_well_height = 0; + + for i in 0..heights.len() { + let left = if i == 0 { + 20 + } else { + heights[i - 1].unwrap_or_else(|| 0) + }; + + let right = if i == heights.len() - 1 { + 20 + } else { + heights[i + 1].unwrap_or_else(|| 0) + }; + + let well_height = if left > right { right } else { left }; + max_well_height = *[ + max_well_height, + well_height - heights[i].unwrap_or_else(|| 0), + ] + .iter() + .max() + .unwrap(); + } + Parameters { total_height, bumpiness, complete_lines, holes: holes as f64, + max_height, + max_well_depth: max_well_height as f64, } } @@ -148,6 +186,10 @@ impl GeneticHeuristicAgent { + other.params.total_height * other_weight, complete_lines: self.params.total_height * self_weight + other.params.total_height * other_weight, + max_height: self.params.max_height * self_weight + + other.params.max_height * other_weight, + max_well_depth: self.params.max_well_depth * self_weight + + other.params.max_well_depth * other_weight, }, } } else {