From d4d137b8cf9aba0c1e3d76e26375b2a175f675cf Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 14 May 2024 01:44:54 +0200 Subject: [PATCH] Iterates and performs ... correctly --- src/main.rs | 2 ++ src/stat_algo.rs | 29 +++++++++++++++++++ src/stat_io.rs | 68 +++++++++++++++++++++++++++++++++++++++++---- src/stat_structs.rs | 1 + src/stats.rs | 58 ++++++++++++++++++++++++++++++-------- 5 files changed, 142 insertions(+), 16 deletions(-) create mode 100644 src/stat_algo.rs create mode 100644 src/stat_structs.rs diff --git a/src/main.rs b/src/main.rs index 2384a27..1b5deb9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,7 +6,9 @@ // #![allow(dead_code)] #![warn(missing_docs)] #![warn(clippy::missing_docs_in_private_items)] +mod stat_algo; mod stat_io; +mod stat_structs; mod stats; mod table_structs; mod table_types; diff --git a/src/stat_algo.rs b/src/stat_algo.rs new file mode 100644 index 0000000..cb6f3d6 --- /dev/null +++ b/src/stat_algo.rs @@ -0,0 +1,29 @@ +//! 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, +} +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), + } + } +} diff --git a/src/stat_io.rs b/src/stat_io.rs index 364d0b7..4dacbb3 100644 --- a/src/stat_io.rs +++ b/src/stat_io.rs @@ -1,12 +1,15 @@ //! All the struct needed for IO purposes #![allow(dead_code)] // #![allow(clippy::missing_docs_in_private_items)] +use anyhow::anyhow; use std::{fs::File, 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; @@ -22,11 +25,15 @@ impl CreatureCharacteristicsAffinity { fn get_affinity(&self, affinity: AffName) -> Affinity { self.affinity[affinity as usize] } + + // fn fit(&self, stat: AffName) -> _ { + // fit(stat, self.affinity) + // } } #[derive(Debug)] /// A single creature with the needed fields to handle affinity selection -struct Creature { +pub(crate) struct Creature { /// The name of the creature name: String, // id : usize, @@ -56,9 +63,33 @@ impl TryFrom for Creature { } } +/// How much a stat fit into a vec of affinities +fn 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 { - // Get most desired affinity - // Get list of selected affinities + /// 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) + } + + /// Get the stat associated to the given affinity + fn get_stat(&self, stat: AffName) -> Affinity { + self.affinities.get_affinity(stat) + } } impl TryFrom for CreatureCharacteristicsAffinity { @@ -137,6 +168,32 @@ impl CharacCharMatrix { 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() { + v.sort_unstable_by(|(_, v1), (_, v2)| v1.total_cmp(v2)) + } + } + + /// Find a creature having an affinity for the given stat + 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); + } + } + Err(anyhow!("Couldn't reach the specified Fit")) + } + + /// Get a creature by Id + pub(crate) fn get_creature(&self, id: usize) -> &Creature { + &self.creatures[id] + } } impl From> for CharacCharMatrix { @@ -158,8 +215,9 @@ impl From> for CharacCharMatrix { inner[index].push((creature_id, *value)); } } - - Self { inner, creatures } + let mut r = Self { inner, creatures }; + r.init(); + r } } diff --git a/src/stat_structs.rs b/src/stat_structs.rs new file mode 100644 index 0000000..43f2c3b --- /dev/null +++ b/src/stat_structs.rs @@ -0,0 +1 @@ +//! Stats repartition structs diff --git a/src/stats.rs b/src/stats.rs index e4832ae..fd55c31 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -8,11 +8,13 @@ use anyhow::Result; use clap::Args; use crate::{ + stat_algo::Fit, stat_io::{load_stat_records, AffName, CharacCharMatrix}, Config, }; #[derive(Args, Debug)] +/// The configuration struct for the StatSolver pub(crate) struct StatConfig { // #[arg(default_value_t: "data/Book1.csv")] config_path: String, @@ -23,12 +25,14 @@ pub(crate) fn stat_solver(args: &StatConfig, config: &Config) -> Result<()> { let _ = config; let _ = args; let statmatrix = load_stat_records("data/statw.csv").unwrap(); - let sol = solution_from_empty(statmatrix); + // println!("{:#?}", &statmatrix); + let sol = solution_from_empty(&statmatrix); println!("{:?}", sol); + // println!("{:#?}", &statmatrix); Ok(()) } -fn solution_from_empty(statmatrix: CharacCharMatrix) -> Result<()> { +fn solution_from_empty(statmatrix: &CharacCharMatrix) -> Result<()> { // while statmatrix.not_filled() {} let stats = vec![ (AffName::F, 4), @@ -39,15 +43,51 @@ fn solution_from_empty(statmatrix: CharacCharMatrix) -> Result<()> { (AffName::Vol, 1), ]; - println!("{:#?}", stats); - let mut sw = StatWeightList::from(stats).iter_cycle(); - println!("{:#?}", sw); - for i in 0..statmatrix.size_loop() { - println!("{:#?}", sw.next()); + // println!("{:#?}", statmatrix); + let sw = StatWeightList::from(stats).iter_cycle(); + let fits = find_all_fit(statmatrix, sw); + + 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 @@ -61,10 +101,6 @@ impl StatWeightList { } } -// impl StatWeight { - -// } - impl From for StatWeightList { fn from(mut value: StatWeightsTuple) -> Self { let ln = value.iter().rfold(0, |acc, (_, w)| acc + w);