Iterates and performs ... correctly

This commit is contained in:
Dandaedre 2024-05-14 01:44:54 +02:00
parent abf04e4fef
commit d4d137b8cf
5 changed files with 142 additions and 16 deletions

View File

@ -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;

29
src/stat_algo.rs Normal file
View File

@ -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<Fit> {
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),
}
}
}

View File

@ -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<StringRecord> 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<StringRecord> 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<usize> {
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<Vec<Creature>> for CharacCharMatrix {
@ -158,8 +215,9 @@ impl From<Vec<Creature>> for CharacCharMatrix {
inner[index].push((creature_id, *value));
}
}
Self { inner, creatures }
let mut r = Self { inner, creatures };
r.init();
r
}
}

1
src/stat_structs.rs Normal file
View File

@ -0,0 +1 @@
//! Stats repartition structs

View File

@ -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<IntoIter<AffName>>) -> 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<IntoIter<AffName>>,
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<StatWeightsTuple> for StatWeightList {
fn from(mut value: StatWeightsTuple) -> Self {
let ln = value.iter().rfold(0, |acc, (_, w)| acc + w);