refactor: ♻️ all for loops are now iterator except basic counters

This commit is contained in:
Ahmet Kaan GÜMÜŞ 2024-11-20 00:20:40 +03:00
parent 7525f92b0d
commit 2d06d28c7b
3 changed files with 50 additions and 36 deletions

View file

@ -24,7 +24,7 @@ impl Bee {
let probabilities = food_sources let probabilities = food_sources
.iter() .iter()
.map(|x| x.fitness_calculation / total_fitness) .map(|food_source| food_source.fitness_calculation / total_fitness)
.collect::<Vec<f64>>(); .collect::<Vec<f64>>();
let onlooker_bee_count = input.food_source_number; let onlooker_bee_count = input.food_source_number;

View file

@ -42,11 +42,10 @@ impl FoodSource {
} }
fn calculate(decision_variables: Vec<f64>) -> f64 { fn calculate(decision_variables: Vec<f64>) -> f64 {
let mut result = 0.0; decision_variables
for element in decision_variables { .iter()
result += element * element; .map(|element| element * element)
} .sum()
result
} }
pub fn create_food_sources( pub fn create_food_sources(
@ -68,7 +67,11 @@ impl FoodSource {
pub fn find_best_food_source(food_sources: &[FoodSource]) -> FoodSource { pub fn find_best_food_source(food_sources: &[FoodSource]) -> FoodSource {
food_sources food_sources
.iter() .iter()
.max_by(|x, y| x.fitness_calculation.total_cmp(&y.fitness_calculation)) .max_by(|food_source_one, food_source_two| {
food_source_one
.fitness_calculation
.total_cmp(&food_source_two.fitness_calculation)
})
.unwrap() .unwrap()
.clone() .clone()
} }
@ -77,7 +80,11 @@ impl FoodSource {
let (most_tried_food_source_index, _) = food_sources let (most_tried_food_source_index, _) = food_sources
.iter() .iter()
.enumerate() .enumerate()
.max_by(|(_, x), (_, y)| x.try_counter.cmp(&y.try_counter)) .max_by(|(_, food_source_one), (_, food_source_two)| {
food_source_one
.try_counter
.cmp(&food_source_two.try_counter)
})
.unwrap(); .unwrap();
most_tried_food_source_index most_tried_food_source_index
} }
@ -90,9 +97,9 @@ impl fmt::Display for FoodSource {
"function_calculation = {:e}\nfitness_calculation = {:e}\ncoordinates = [", "function_calculation = {:e}\nfitness_calculation = {:e}\ncoordinates = [",
self.function_calculation, self.fitness_calculation self.function_calculation, self.fitness_calculation
)?; )?;
for coordinate in &self.coordinates { self.coordinates
writeln!(f, " {:e},", coordinate)?; .iter()
} .try_for_each(|coordinate| writeln!(f, " {:e},", coordinate))?;
write!(f, "]\ntry_counter = {}\n", self.try_counter) write!(f, "]\ntry_counter = {}\n", self.try_counter)
} }
} }

View file

@ -20,16 +20,18 @@ pub struct Input {
impl Input { impl Input {
pub fn get() -> Self { pub fn get() -> Self {
let mut read_file = false; let mut read_file = false;
for arg in args().collect::<Vec<String>>() {
match arg.as_str() { args()
.collect::<Vec<String>>()
.iter()
.for_each(|arg| match arg.as_str() {
"-r" | "--read_file" => read_file = true, "-r" | "--read_file" => read_file = true,
"-h" | "--help" => { "-h" | "--help" => {
show_help(); show_help();
exit(0); exit(0);
} }
_ => {} _ => {}
} });
}
if read_file { if read_file {
Input::read_config_file_input() Input::read_config_file_input()
@ -84,13 +86,19 @@ impl Input {
let config_file = File::open("abc_config.toml").unwrap(); let config_file = File::open("abc_config.toml").unwrap();
let reader = BufReader::new(config_file); let reader = BufReader::new(config_file);
let mut words = vec![]; let mut words = vec![];
for line in reader.lines().map(|x| x.unwrap()).collect::<Vec<String>>() { reader
let mut parsed = line .lines()
.map(|unchecked_line| unchecked_line.unwrap())
.collect::<Vec<String>>()
.iter()
.for_each(|line| {
words.append(
&mut line
.split('=') .split('=')
.map(|x| x.trim().to_string()) .map(|splitted| splitted.trim().to_string())
.collect::<Vec<String>>(); .collect::<Vec<String>>(),
words.append(&mut parsed); )
} });
if words[0].as_str() == "[start_parameters]" { if words[0].as_str() == "[start_parameters]" {
for i in (1..words.len()).step_by(2) { for i in (1..words.len()).step_by(2) {
match words[i].as_str() { match words[i].as_str() {
@ -129,12 +137,13 @@ pub fn give_output(
run_counter: usize, run_counter: usize,
) { ) {
let mut write_file = false; let mut write_file = false;
for arg in args().collect::<Vec<String>>() { args()
match arg.as_str() { .collect::<Vec<String>>()
.iter()
.for_each(|arg| match arg.as_str() {
"-w" | "--write_file" => write_file = true, "-w" | "--write_file" => write_file = true,
_ => {} _ => {}
} });
}
let mut print_buffer = vec![]; let mut print_buffer = vec![];
write!(print_buffer, "[{}]\n{}\n", run_counter, best_food_source).unwrap(); write!(print_buffer, "[{}]\n{}\n", run_counter, best_food_source).unwrap();
@ -194,19 +203,17 @@ fn write_output_file(print_buffer: &[u8], run_counter: usize) {
} }
fn arithmetic_mean(results: &[f64]) -> f64 { fn arithmetic_mean(results: &[f64]) -> f64 {
let mut total_results = 0.0; results.iter().sum::<f64>() / results.len() as f64
for function_result in results {
total_results += function_result
}
total_results / results.len() as f64
} }
fn standard_deviation(results: &[f64], arithmetic_mean: f64) -> f64 { fn standard_deviation(results: &[f64], arithmetic_mean: f64) -> f64 {
let mut total_difference_square = 0.0; f64::sqrt(
for function_result in results { results
total_difference_square += (function_result - arithmetic_mean).powi(2) .iter()
} .map(|function_result| (function_result - arithmetic_mean).powi(2))
f64::sqrt(total_difference_square / (results.len() - 1) as f64) .sum::<f64>()
/ (results.len() - 1) as f64,
)
} }
fn show_help() { fn show_help() {