Adds a cyclic operator and some process

This commit is contained in:
Dandaedre 2024-05-09 04:55:34 +02:00
parent 621e82e8b6
commit abf04e4fef
2 changed files with 110 additions and 35 deletions

View File

@ -1,7 +1,7 @@
//! All the struct needed for IO purposes
#![allow(dead_code)]
#![allow(clippy::missing_docs_in_private_items)]
use std::{collections::HashMap, fs::File, path::Path};
// #![allow(clippy::missing_docs_in_private_items)]
use std::{fs::File, path::Path};
use anyhow::{Context, Result};
use csv::StringRecord;
@ -13,21 +13,28 @@ type Affinity = f64;
#[derive(Serialize, Deserialize, Debug)]
/// A row representing the creature affinity for a stat
struct CreatureCharacteristicsAffinity {
/// A list of witch stats are desired and at witch level
affinity: Vec<Affinity>,
}
impl CreatureCharacteristicsAffinity {
/// Get the affinity level on the given stat
fn get_affinity(&self, affinity: AffName) -> Affinity {
self.affinity[affinity as usize]
}
}
#[derive(Debug)]
/// A single creature with the needed fields to handle affinity selection
struct Creature {
/// The name of the creature
name: String,
// id : usize,
/// The list of affinity desired
affinities: CreatureCharacteristicsAffinity,
/// The actives affinities ?
actives_affinities: Vec<Affinity>,
/// The currently selected affinities
selected_affinities: Vec<AffName>,
}
@ -68,8 +75,9 @@ impl TryFrom<StringRecord> for CreatureCharacteristicsAffinity {
}
/// The names of all affinities (essentialy a list of characteristics)
#[derive(Deserialize, Serialize, Debug)]
enum AffName {
#[allow(clippy::missing_docs_in_private_items)]
#[derive(Deserialize, Serialize, Debug, Clone, Copy)]
pub(crate) enum AffName {
F,
Ag,
Per,
@ -81,37 +89,55 @@ enum AffName {
}
#[inline]
/// Shortcut to get the affinity
fn get_aff_index(affinity: AffName) -> usize {
affinity as usize
}
#[derive(Deserialize, Serialize)]
struct Solution {
creature: String,
affinities: CreatureCharacteristicsAffinity,
picks: Vec<AffName>,
}
// #[derive(Deserialize, Serialize)]
// /// A solution for the creature
// struct Solution {
// creature: String,
// affinities: CreatureCharacteristicsAffinity,
// picks: Vec<AffName>,
// }
impl CreatureCharacteristicsAffinity {
// Create an affinity from a record
}
/// The list of all creature and their associated affinities
struct CreaturesAffinity {
list_creatures: HashMap<AffName, CreatureCharacteristicsAffinity>,
matrix: CharacCharMatrix,
}
// /// The list of all creature and their associated affinities
// struct CreaturesAffinity {
// list_creatures: HashMap<AffName, CreatureCharacteristicsAffinity>,
// matrix: CharacCharMatrix,
// }
#[derive(Debug)]
/// A matrix representing: List of characteristics and associated list of creatures
/// All math is done at this level to avoid cost
/// Right now the index of every creature is used in the matrix, but a references could be used instead
struct CharacCharMatrix {
pub(crate) struct CharacCharMatrix {
/// The inner vector structure, used to access rapidly the underlying affinities
inner: Vec<Vec<(usize, Affinity)>>,
/// A translation vector to remember what is what
creatures: Vec<Creature>,
}
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
}
}
impl From<Vec<Creature>> for CharacCharMatrix {
fn from(creatures: Vec<Creature>) -> Self {
@ -127,7 +153,6 @@ impl From<Vec<Creature>> for CharacCharMatrix {
Vec::<(usize, Affinity)>::with_capacity(size),
];
println!("I: {:?}", creatures);
for (creature_id, creature) in creatures.iter().enumerate() {
for (index, value) in creature.affinities.affinity.iter().enumerate() {
inner[index].push((creature_id, *value));
@ -139,12 +164,12 @@ impl From<Vec<Creature>> for CharacCharMatrix {
}
/// Load all the records in the csv
pub fn load_stat_records<T>(filename: T) -> Result<()>
pub fn load_stat_records<T>(filename: T) -> Result<CharacCharMatrix>
where
T: AsRef<Path>,
{
let file = File::open(filename)?;
let mut rdr = csv::ReaderBuilder::new()
let rdr = csv::ReaderBuilder::new()
.has_headers(true)
.delimiter(b',')
.double_quote(false)
@ -152,24 +177,12 @@ where
.flexible(true)
.comment(Some(b'#'))
.from_reader(file);
println!("{:?}", rdr);
println!("{:?}", rdr.headers().cloned());
// for rec in rdr.into_records() {
// println!("{:?}", rec);
// println!("{:?}", CreatureCharacteristicsAffinity::try_from(rec?));
// }
// let creatures_aff: Vec<CreatureCharacteristicsAffinity> = rdr
// .into_records()
// .flat_map(|c| CreatureCharacteristicsAffinity::try_from(c.unwrap()))
// .collect();
// println!("{:#?}", creatures_aff);
let creatures: Vec<Creature> = rdr
.into_records()
.flat_map(|c| Creature::try_from(c.unwrap()))
.collect();
let creature_matrix = CharacCharMatrix::from(creatures);
println!("{:#?}", creature_matrix);
Ok(())
// println!("{:#?}", creature_matrix);
Ok(creature_matrix)
}

View File

@ -2,10 +2,15 @@
#![allow(dead_code)]
#![allow(clippy::missing_docs_in_private_items)]
use std::{iter::Cycle, vec::IntoIter};
use anyhow::Result;
use clap::Args;
use crate::{stat_io::load_stat_records, Config};
use crate::{
stat_io::{load_stat_records, AffName, CharacCharMatrix},
Config,
};
#[derive(Args, Debug)]
pub(crate) struct StatConfig {
@ -17,10 +22,67 @@ pub(crate) struct StatConfig {
pub(crate) fn stat_solver(args: &StatConfig, config: &Config) -> Result<()> {
let _ = config;
let _ = args;
let _ = load_stat_records("data/statw.csv");
let statmatrix = load_stat_records("data/statw.csv").unwrap();
let sol = solution_from_empty(statmatrix);
println!("{:?}", sol);
Ok(())
}
fn solution_from_empty(statmatrix: CharacCharMatrix) -> Result<()> {
// while statmatrix.not_filled() {}
let stats = vec![
(AffName::F, 4),
(AffName::Ag, 3),
(AffName::Per, 3),
(AffName::Psy, 3),
(AffName::Int, 1),
(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());
}
Ok(())
}
type StatWeightsTuple = Vec<(AffName, usize)>;
/// The statweights, holding looping methods
#[derive(Debug)]
struct StatWeightList {
weights: Vec<AffName>,
}
impl StatWeightList {
fn iter_cycle(self) -> Cycle<IntoIter<AffName>> {
self.weights.into_iter().cycle()
}
}
// impl StatWeight {
// }
impl From<StatWeightsTuple> 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 {