From 51f5e6753e94c0b35c5271dee4b71fbea2e897ba Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 14 May 2024 22:09:22 +0200 Subject: [PATCH] Huge leap in cleaning --- src/stat_algo.rs | 150 ++++++++++++++++++---- src/stat_io.rs | 302 ++++++++++++++++++++++++++++++++++---------- src/stat_structs.rs | 82 ++++++++++++ src/stats.rs | 157 ++++------------------- 4 files changed, 473 insertions(+), 218 deletions(-) diff --git a/src/stat_algo.rs b/src/stat_algo.rs index cb6f3d6..5e3d184 100644 --- a/src/stat_algo.rs +++ b/src/stat_algo.rs @@ -1,29 +1,133 @@ //! The stat repartition algorithm -#[allow(dead_code)] -/// How much a solution fits the algorithm, or how much a solution fits a creature -#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] -pub enum Fit { - /// Weakest fit, can't be used - VeryWeak, - /// Weak fit, shouldn't be used - Weak, - /// Average fit, can be used - Medium, - /// Strong fit, will always be used - Strong, - /// Best fit, must use - VeryStrong, +use std::{iter::Cycle, vec::IntoIter}; + +use crate::stat_io::{AffName, CharacCharMatrix}; +use crate::stat_structs::Fit; +use anyhow::anyhow; +use anyhow::Result; + +/// Fitness mode +#[derive(Debug, Clone, Copy)] +pub(crate) enum Mode { + /// A positive fitness, looking for stats the creature has affinity with + Positive, + /// A negative fitness, looking for stats the creature has no affinity with + Negative, } -impl Fit { - /// Lower the fitness by one - pub(crate) fn lower(&self) -> Option { - match self { - Fit::VeryWeak => None, - Fit::Weak => Some(Fit::VeryWeak), - Fit::Medium => Some(Fit::Weak), - Fit::Strong => Some(Fit::Medium), - Fit::VeryStrong => Some(Fit::Strong), + +/// Find all the fits for the solution (algo1) +pub(crate) fn find_all_fits( + statmatrix: &mut CharacCharMatrix, + mut sw: Cycle>, + mode: Mode, +) -> Result<()> { + let (mut fits, mut desired_fit_level) = match mode { + Mode::Positive => (statmatrix.size_loop(), Some(Fit::Strong)), + Mode::Negative => (statmatrix.size_unfited_loop(), Some(Fit::VeryWeak)), + }; + while fits > 0 { + if let Some(fit_level) = desired_fit_level { + (fits, desired_fit_level) = match mode { + Mode::Positive => ( + find_stat_fit(statmatrix, &mut sw, &fit_level, fits, mode), + fit_level.lower(None), + ), + Mode::Negative => ( + find_stat_fit(statmatrix, &mut sw, &fit_level, fits, mode), + fit_level.upper(None), + ), + } + } else { + return Err(anyhow!( + "Can't find any ({:?}) fit at any level, please examine the remaining unfitted characters" + ,mode)); } } + Ok(()) +} + +// /// Find all the fits for the solution (algo1) +// pub(crate) fn find_all_negative_fits( +// statmatrix: &mut CharacCharMatrix, +// mut sw: Cycle>, +// ) -> Result<()> { +// let mut fits = statmatrix.size_unfited_loop(); +// let mut desired_fit_level = Some(Fit::VeryWeak); +// while fits > 0 { +// if let Some(fit_level) = desired_fit_level { +// fits = find_stat_unfit(statmatrix, &mut sw, &fit_level, fits); +// desired_fit_level = fit_level.upper(); +// } else { +// return Err(anyhow!( +// "Can't find any fit at any level, please examine the remaining unfitted characters" +// )); +// } +// } +// Ok(()) +// } + +/// Number of value that couldn't have a fit +type NbUnfit = usize; + +/// Find a stat that fits the given affinity +fn find_stat_fit( + statmatrix: &mut CharacCharMatrix, + stat: &mut Cycle>, + fit_level: &Fit, + iterations: usize, + mode: Mode, +) -> NbUnfit { + let mut unfit = 0; + // All iteration to do + for _ in 0..iterations { + let stat = stat.next().unwrap(); + // Iterate every creature this part of the algorithm is unneeded for our fitness function + // as the fitness doesn't depend on the creature + if test_fit_for_all_creatures(statmatrix, stat, fit_level, mode).is_err() { + unfit += 1; + } + } + println!( + "[{}] stats couldn't be [{:?}] fitted at level {:?}", + unfit, mode, fit_level + ); + unfit +} + +/// Iterate the fitness on every creature +/// Useless for our fitness algorithm +fn test_fit_for_all_creatures( + statmatrix: &mut CharacCharMatrix, + stat: AffName, + fit_level: &Fit, + mode: Mode, +) -> Result<()> { + for _ in 0..statmatrix.get_len_affinity(stat) { + let found = match mode { + Mode::Negative => statmatrix.find_creature_for_stat_with_negative_fit(stat, fit_level), + Mode::Positive => statmatrix.find_creature_for_stat_with_fit(stat, fit_level), + }; + + if let Ok(creature_id) = found { + statmatrix + .add_affinity_to_creature(statmatrix.to_vec_id(creature_id, stat), stat) + .unwrap(); + + println!( + "Found creature {:?} to be a [{:?}] fit for stat {:?} with fitness {:?}", + // statmatrix.creature_name(creature_id), + creature_id, + mode, + stat, + fit_level + ); + return Ok(()); + } + } + Err(anyhow!( + "No creature can fit the charac {:?} at fitness {:?}", + stat, + fit_level + )) } diff --git a/src/stat_io.rs b/src/stat_io.rs index 4dacbb3..562567f 100644 --- a/src/stat_io.rs +++ b/src/stat_io.rs @@ -1,15 +1,12 @@ //! All the struct needed for IO purposes -#![allow(dead_code)] -// #![allow(clippy::missing_docs_in_private_items)] +use crate::stat_structs::Fit; use anyhow::anyhow; -use std::{fs::File, path::Path}; +use std::{fmt::Display, fs::File, iter::zip, path::Path}; use anyhow::{Context, Result}; use csv::StringRecord; use serde::{Deserialize, Serialize}; -use crate::stat_algo::Fit; - /// How to represent mathematically the affinity for a stat type Affinity = f64; @@ -20,6 +17,19 @@ struct CreatureCharacteristicsAffinity { affinity: Vec, } +impl Display for CreatureCharacteristicsAffinity { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + zip(&self.affinity, AffName::as_iter()) + .map(|(val, aname)| format!("[{:?}]: {}", aname, val)) + .collect::>() + .join(","), + ) + } +} + impl CreatureCharacteristicsAffinity { /// Get the affinity level on the given stat fn get_affinity(&self, affinity: AffName) -> Affinity { @@ -36,11 +46,10 @@ impl CreatureCharacteristicsAffinity { pub(crate) struct Creature { /// The name of the creature name: String, - // id : usize, /// The list of affinity desired affinities: CreatureCharacteristicsAffinity, - /// The actives affinities ? - actives_affinities: Vec, + // /// The actives affinities ? + // actives_affinities: Vec, /// The currently selected affinities selected_affinities: Vec, } @@ -57,7 +66,7 @@ impl TryFrom for Creature { Ok(Self { name: creature.to_owned(), affinities: CreatureCharacteristicsAffinity { affinity: aff }, - actives_affinities: Vec::new(), + // actives_affinities: Vec::new(), selected_affinities: Vec::new(), }) } @@ -78,18 +87,52 @@ fn fit(value: Affinity, _vaff: &[Affinity]) -> Fit { Fit::VeryWeak } } +// fn negative_fit(value: Affinity, _vaff: &[Affinity]) -> Fit { +// // For now ignore the other affinities +// if value >= 5. { +// Fit::VeryStrong +// } else if value >= 4. { +// Fit::Strong +// } else if value >= 3. { +// Fit::Medium +// } else if value >= 1. { +// Fit::Weak +// } else { +// Fit::VeryWeak +// } +// } impl Creature { /// Return the fit of a stat pub(crate) fn fit(&self, stat: AffName) -> Fit { - let stat = self.get_stat(stat); - fit(stat, &self.affinities.affinity) + fit(self.get_stat(stat), &self.affinities.affinity) } + /// Return the negative fitness of a stat + pub(crate) fn negative_fit(&self, stat: AffName) -> Fit { + fit(self.get_stat(stat), &self.affinities.affinity) + } /// Get the stat associated to the given affinity fn get_stat(&self, stat: AffName) -> Affinity { self.affinities.get_affinity(stat) } + + /// Add the given affinity to the list of affinities (Unckecked) + fn add_affinity(&mut self, stat: AffName) { + self.selected_affinities.push(stat); + } + + /// Can the stat be picked positively (aka, test the length and wether the stat was already selected) + #[deprecated] + fn can_pick(&self, stat: AffName) -> bool { + self.selected_affinities.len() < 2 && !self.selected_affinities.contains(&stat) + } + + /// Can the stat be picked negatively (aka, is the length ok and does the vector already contains the value) + #[deprecated] + fn can_pick_negatively(&self, stat: AffName) -> bool { + self.selected_affinities.len() < 3 && !self.selected_affinities.contains(&stat) + } } impl TryFrom for CreatureCharacteristicsAffinity { @@ -107,7 +150,7 @@ impl TryFrom for CreatureCharacteristicsAffinity { /// The names of all affinities (essentialy a list of characteristics) #[allow(clippy::missing_docs_in_private_items)] -#[derive(Deserialize, Serialize, Debug, Clone, Copy)] +#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum AffName { F, Ag, @@ -119,29 +162,54 @@ pub(crate) enum AffName { Chr, } -#[inline] -/// Shortcut to get the affinity -fn get_aff_index(affinity: AffName) -> usize { - affinity as usize +impl AffName { + /// Return the list of stats as iterable + pub(crate) fn as_iter() -> impl Iterator { + [ + AffName::F, + AffName::Ag, + AffName::Per, + AffName::Psy, + AffName::Int, + AffName::Vol, + AffName::Chn, + AffName::Chr, + ] + .iter() + .copied() + } } -// #[derive(Deserialize, Serialize)] -// /// A solution for the creature -// struct Solution { -// creature: String, -// affinities: CreatureCharacteristicsAffinity, -// picks: Vec, -// } +/// A creature id in the vector of creatures +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) struct CreatureVecId(usize); -impl CreatureCharacteristicsAffinity { - // Create an affinity from a record +/// A creature id in the inner vector +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct CreatureInnerId(usize); + +impl CreatureInnerId { + fn id(self) -> usize { + self.0 + } } -// /// The list of all creature and their associated affinities -// struct CreaturesAffinity { -// list_creatures: HashMap, -// matrix: CharacCharMatrix, -// } +impl CreatureVecId { + fn id(self) -> usize { + self.0 + } +} + +impl Into for usize { + fn into(self) -> CreatureInnerId { + CreatureInnerId(self) + } +} +impl Into for usize { + fn into(self) -> CreatureVecId { + CreatureVecId(self) + } +} #[derive(Debug)] /// A matrix representing: List of characteristics and associated list of creatures @@ -149,26 +217,11 @@ impl CreatureCharacteristicsAffinity { /// Right now the index of every creature is used in the matrix, but a references could be used instead pub(crate) struct CharacCharMatrix { /// The inner vector structure, used to access rapidly the underlying affinities - inner: Vec>, - /// A translation vector to remember what is what + inner: Vec>, + /// The list of creatures refered to by the inner structure creatures: Vec, } impl CharacCharMatrix { - /// Check if the matrix is filled - pub(crate) fn not_filled(&self) -> bool { - for elt in &self.creatures { - if elt.selected_affinities.len() < 2 { - return false; - } - } - true - } - - /// Gives the size of the loop needed to fill all element - pub(crate) fn size_loop(&self) -> usize { - self.creatures.len() * 2 - } - /// Initialize the charac matrix by sorting it fn init(&mut self) { for v in self.inner.iter_mut() { @@ -177,22 +230,144 @@ impl CharacCharMatrix { } /// Find a creature having an affinity for the given stat + /// Returns the id in the inner struct pub(crate) fn find_creature_for_stat_with_fit( &self, stat: AffName, - strong: &Fit, - ) -> Result { - for (creature, _affinity) in self.inner[stat as usize].iter() { - if self.creatures[*creature].fit(stat) >= *strong { - return Ok(*creature); + fit_level: &Fit, + ) -> Result { + for (i, (creature, _affinity)) in self.inner[stat as usize].iter().enumerate() { + if self.available(*creature, stat, *fit_level).is_ok() { + return Ok(i.into()); } } Err(anyhow!("Couldn't reach the specified Fit")) } + /// Find a create with a negative fit for a stat + /// Returns the id in the inner struct + pub(crate) fn find_creature_for_stat_with_negative_fit( + &self, + stat: AffName, + fit_level: &Fit, + ) -> Result { + for (i, (creature, _)) in self.inner[stat as usize].iter().rev().enumerate() { + if self.available_negative(*creature, stat, *fit_level).is_ok() { + return Ok(i.into()); + } + } + Err(anyhow!("Coudln't find a match at the given negative fit")) + } /// Get a creature by Id - pub(crate) fn get_creature(&self, id: usize) -> &Creature { - &self.creatures[id] + pub(crate) fn get_creature(&self, id: CreatureVecId) -> &Creature { + &self.creatures[id.id()] + } + /// Get a mutable reference to the creature by Id + pub(crate) fn get_mut_creature(&mut self, id: CreatureVecId) -> &mut Creature { + &mut self.creatures[id.id()] + } + + /// Get the creature name + #[allow(dead_code)] + pub(crate) fn creature_name(&self, id: CreatureVecId) -> &String { + &self.get_creature(id).name + } + + /// Adds the affinity given to a creature + pub(crate) fn add_affinity_to_creature( + &mut self, + id: CreatureVecId, + stat: AffName, + ) -> Result<()> { + self.get_mut_creature(id).add_affinity(stat); + Ok(()) + } + + /// Returns Ok() if the creature can fit the stat at the fit level Err otherwise + fn available(&self, id: CreatureVecId, stat: AffName, fit: Fit) -> Result<()> { + let creature = self.get_creature(id); + if creature.fit(stat) >= fit && creature.can_pick(stat) { + Ok(()) + } else { + Err(anyhow!( + "Creature {:?} can't find a fit for {:?} with affinity {:?}", + creature, + stat, + fit + )) + } + } + /// Returns Ok() if the creature can fit the negative stat at the fit level Err otherwise + fn available_negative(&self, id: CreatureVecId, stat: AffName, fit: Fit) -> Result<()> { + let creature = self.get_creature(id); + if creature.negative_fit(stat) <= fit && creature.can_pick_negatively(stat) { + Ok(()) + } else { + Err(anyhow!( + "Creature {:?} can't find a negative fit for {:?} with affinity {:?}", + creature, + stat, + fit + )) + } + } + + /// Show the list of solutions chosen for each creature + pub(crate) fn print_solutions(&self) { + for creature in self.creatures.iter() { + println!( + "[{}] Les Caractéristiques maximum à la création : {:?} (7), {:?} (7), {:?} (5)", + creature.name, + creature.selected_affinities[0], + creature.selected_affinities[1], + creature.selected_affinities[2] + ) + } + } + + /// Print all stat weights + pub(crate) fn print_weights(&self) { + for creature in self.creatures.iter() { + println!("[{}] {}", creature.name, creature.affinities); + } + } + + /// Gives the size of the loop needed to fill all negative characteristics + pub(crate) fn size_unfited_loop(&self) -> usize { + self.creatures.len() + } + + /// Gives the size of the loop needed to fill all characteristics + pub(crate) fn size_loop(&self) -> usize { + self.creatures.len() * 2 + } + + /// Get the length of the affinity vector related to the given stat + pub(crate) fn get_len_affinity(&self, stat: AffName) -> usize { + self.get_affinity(stat).len() + } + + /// Get a reference to an affinity vector + fn get_affinity(&self, stat: AffName) -> &Vec<(CreatureVecId, f64)> { + &self.inner[stat as usize] + } + + /// Find the id in the vector associated to the inner id + pub(crate) fn to_vec_id(&self, creature_id: CreatureInnerId, stat: AffName) -> CreatureVecId { + self.inner[stat as usize][creature_id.id()].0 + } + + #[deprecated] + /// Find the inner id associated to the creature_id give + pub(crate) fn to_inner_id(&self, creature_id: CreatureVecId, stat: AffName) -> CreatureInnerId { + let a = &self.creatures[creature_id.id()]; + // self.inner[stat as usize] + // .iter() + // .find(|(id, _)| &creature_id == id) + // .and_then(|(id, _)| Some(*id)) + // .unwrap() + + todo!() } } @@ -200,19 +375,19 @@ impl From> for CharacCharMatrix { fn from(creatures: Vec) -> Self { let size = creatures.len() + 1; let mut inner = vec![ - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), - Vec::<(usize, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), + Vec::<(CreatureVecId, Affinity)>::with_capacity(size), ]; for (creature_id, creature) in creatures.iter().enumerate() { for (index, value) in creature.affinities.affinity.iter().enumerate() { - inner[index].push((creature_id, *value)); + inner[index].push((creature_id.into(), *value)); } } let mut r = Self { inner, creatures }; @@ -241,6 +416,5 @@ where .flat_map(|c| Creature::try_from(c.unwrap())) .collect(); let creature_matrix = CharacCharMatrix::from(creatures); - // println!("{:#?}", creature_matrix); Ok(creature_matrix) } diff --git a/src/stat_structs.rs b/src/stat_structs.rs index 43f2c3b..7a74f61 100644 --- a/src/stat_structs.rs +++ b/src/stat_structs.rs @@ -1 +1,83 @@ //! Stats repartition structs + +use std::{iter::Cycle, vec::IntoIter}; + +use crate::stat_io::AffName; +/// How much a solution fits the algorithm, or how much a solution fits a creature +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] +pub(crate) enum Fit { + /// Weakest fit, can't be used + VeryWeak, + /// Weak fit, shouldn't be used + Weak, + /// Average fit, can be used + Medium, + /// Strong fit, will always be used + Strong, + /// Best fit, must use + VeryStrong, +} +impl Fit { + /// Lower the fitness by one, with an optionnal maximum + pub(crate) fn lower(&self, min: Option) -> Option { + let f = match self { + Fit::VeryWeak => None, + Fit::Weak => Some(Fit::VeryWeak), + Fit::Medium => Some(Fit::Weak), + Fit::Strong => Some(Fit::Medium), + Fit::VeryStrong => Some(Fit::Strong), + }; + if f <= min { + return None; + } + f + } + + /// Raise the fitness level by one, with an optionnal maximum + pub(crate) fn upper(&self, min: Option) -> Option { + let f = match self { + Fit::VeryWeak => Some(Fit::Weak), + Fit::Weak => Some(Fit::Medium), + Fit::Medium => Some(Fit::Strong), + Fit::Strong => Some(Fit::VeryStrong), + Fit::VeryStrong => None, + }; + if f <= min { + return None; + } + f + } +} +/// A stat weight level (Affinity name and weight) +type StatWeightsTuple = Vec<(AffName, usize)>; + +/// The statweights, holding looping methods +#[derive(Debug)] +pub(crate) struct StatWeightList { + /// The list of all affinities + weights: Vec, +} +impl StatWeightList { + /// Iterate over all affinites to fill, endlessly + pub(crate) fn iter_cycle(self) -> Cycle> { + self.weights.into_iter().cycle() + } +} + +impl From for StatWeightList { + fn from(mut value: StatWeightsTuple) -> Self { + let ln = value.iter().rfold(0, |acc, (_, w)| acc + w); + let mut weights = Vec::with_capacity(ln); + let mut i = 0; + while i < ln { + for (w, nb) in value.iter_mut() { + if nb != &0 { + *nb -= 1; + weights.push(*w); + i += 1; + } + } + } + Self { weights } + } +} diff --git a/src/stats.rs b/src/stats.rs index fd55c31..ae5358b 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -1,14 +1,13 @@ //! A module to handle stats disparity between all origins -#![allow(dead_code)] -#![allow(clippy::missing_docs_in_private_items)] -use std::{iter::Cycle, vec::IntoIter}; +use crate::stat_algo::find_all_fits; +use crate::stat_algo::Mode; +use crate::stat_structs::StatWeightList; use anyhow::Result; use clap::Args; use crate::{ - stat_algo::Fit, stat_io::{load_stat_records, AffName, CharacCharMatrix}, Config, }; @@ -17,24 +16,24 @@ use crate::{ /// The configuration struct for the StatSolver pub(crate) struct StatConfig { // #[arg(default_value_t: "data/Book1.csv")] + /// The path where the data to analyse is config_path: String, } /// Main solver function, in charge of selecting algorithms and handling all program flow pub(crate) fn stat_solver(args: &StatConfig, config: &Config) -> Result<()> { let _ = config; - let _ = args; - let statmatrix = load_stat_records("data/statw.csv").unwrap(); - // println!("{:#?}", &statmatrix); - let sol = solution_from_empty(&statmatrix); - println!("{:?}", sol); - // println!("{:#?}", &statmatrix); + let mut statmatrix = load_stat_records(&args.config_path).unwrap(); + solution_from_empty(&mut statmatrix).unwrap(); + println!("{:?}", statmatrix.print_weights()); + println!("{:?}", statmatrix.print_solutions()); Ok(()) } -fn solution_from_empty(statmatrix: &CharacCharMatrix) -> Result<()> { +/// Find a solution from an empty solution (algo1) +fn solution_from_empty(statmatrix: &mut CharacCharMatrix) -> Result<()> { // while statmatrix.not_filled() {} - let stats = vec![ + let stats_desired = vec![ (AffName::F, 4), (AffName::Ag, 3), (AffName::Per, 3), @@ -42,126 +41,22 @@ fn solution_from_empty(statmatrix: &CharacCharMatrix) -> Result<()> { (AffName::Int, 1), (AffName::Vol, 1), ]; + let stats_undesirable = vec![ + (AffName::Int, 3), + (AffName::Vol, 3), + (AffName::Chr, 2), + (AffName::Chn, 2), + (AffName::F, 1), + (AffName::Ag, 1), + (AffName::Per, 1), + (AffName::Psy, 1), + ]; - // println!("{:#?}", statmatrix); - let sw = StatWeightList::from(stats).iter_cycle(); - let fits = find_all_fit(statmatrix, sw); + let sw = StatWeightList::from(stats_desired).iter_cycle(); + let nsw = StatWeightList::from(stats_undesirable).iter_cycle(); + find_all_fits(statmatrix, sw, Mode::Positive).unwrap(); + find_all_fits(statmatrix, nsw, Mode::Negative).unwrap(); + // find_all_negative_fits(statmatrix, nsw).unwrap(); Ok(()) } - -fn find_all_fit(statmatrix: &CharacCharMatrix, mut sw: Cycle>) -> Result<()> { - let mut fits = statmatrix.size_loop(); - let mut desired_fit_level = Some(Fit::Strong); - while fits > 0 { - if let Some(fit_level) = desired_fit_level { - fits = find_for_fit(statmatrix, &mut sw, &fit_level, fits); - desired_fit_level = fit_level.lower(); - } else { - return Ok(()); - } - } - Ok(()) -} - -fn find_for_fit( - statmatrix: &CharacCharMatrix, - stat: &mut Cycle>, - fit: &Fit, - iterations: usize, -) -> usize { - let mut unfit = 0; - for _ in 0..iterations { - // println!("{:#?}",); - let stat = stat.next().unwrap(); - let found = statmatrix.find_creature_for_stat_with_fit(stat, fit); - if let Ok(creature) = found { - println!( - "Found creature {} to be a fit for stat {:?} with fitness {:?}", - creature, stat, fit - ); - } else { - unfit += 1; - } - } - println!("[{}] stats couldn't be fit at level {:?}", unfit, fit); - unfit -} - -type StatWeightsTuple = Vec<(AffName, usize)>; - -/// The statweights, holding looping methods -#[derive(Debug)] -struct StatWeightList { - weights: Vec, -} -impl StatWeightList { - fn iter_cycle(self) -> Cycle> { - self.weights.into_iter().cycle() - } -} - -impl From for StatWeightList { - fn from(mut value: StatWeightsTuple) -> Self { - let ln = value.iter().rfold(0, |acc, (_, w)| acc + w); - let mut weights = Vec::with_capacity(ln); - let mut i = 0; - while i < ln { - for (w, nb) in value.iter_mut() { - if nb != &0 { - *nb -= 1; - weights.push(*w); - i += 1; - } - } - } - Self { weights } - } -} - -// struct DesiredStats {} - -// struct Creature { -// stats: DesiredStats, -// name: String, -// } - -// enum CharacEnum { -// F, -// Ag, -// } - -// struct CharacWeight { -// charac: CharacEnum, -// list_weights: Vec<(f64, Creature)>, -// } - -// // impl Creature{ -// // fn get_ -// // } - -// // The first Algorithm, creating all creatures from scratch - -// fn get_next_stat_to_grow() {} - -// fn get_greatest_consumer_of(c: CharacEnum) {} - -// fn assign_stat_to_creature(c: CharacEnum) {} - -// fn get_greatest_despiser_of(c: CharacEnum) {} - -// // The second algorithm, appending to an existing solution - -// // Serialize and Deserialize Solutions - -// fn try_getting_desired_stat() {} - -// fn find_swap_creature() {} - -// // Integrity check and disparity check - -// fn check_stats_integrity() {} - -// fn show_stats() {} - -// fn show_outliers() {}