feat: able to give file output

This commit is contained in:
Ahmet Kaan GÜMÜŞ 2024-11-20 00:20:40 +03:00
parent 930223c0eb
commit 2eb0fff95d
4 changed files with 104 additions and 38 deletions

View file

@ -1,3 +1,5 @@
use core::fmt;
use rand::Rng; use rand::Rng;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -55,3 +57,13 @@ impl FoodSource {
food_sources food_sources
} }
} }
impl fmt::Display for FoodSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"fitness = {}\ncoordinates = {:#?}\ntry_counter = {}\n",
self.fitness, self.coordinates, self.try_counter
)
}
}

View file

@ -1,9 +1,11 @@
use std::{ use std::{
env, env::args,
fs::File, fs::{File, OpenOptions},
io::{self, BufRead, BufReader}, io::{self, BufRead, BufReader, Write},
}; };
use food::FoodSource;
pub mod bee; pub mod bee;
pub mod food; pub mod food;
@ -18,13 +20,15 @@ pub struct Input {
} }
impl Input { impl Input {
pub fn get() -> Self { pub fn get() -> Self {
let args = env::args().collect::<Vec<String>>(); let mut read_file = false;
if args.len() > 1 { for arg in args().collect::<Vec<String>>() {
if args[1] == "-f" || args[1] == "--file" { match arg.as_str() {
Input::read_config_file_input() "-r" | "--read-file" => read_file = true,
} else { _ => {}
Input::user_interactive_input()
} }
}
if read_file {
Input::read_config_file_input()
} else { } else {
Input::user_interactive_input() Input::user_interactive_input()
} }
@ -73,7 +77,7 @@ impl Input {
run: 0, run: 0,
}; };
let config_file = File::open("abc.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>>() { for line in reader.lines().map(|x| x.unwrap()).collect::<Vec<String>>() {
@ -83,11 +87,8 @@ impl Input {
.collect::<Vec<String>>(); .collect::<Vec<String>>();
words.append(&mut parsed); words.append(&mut parsed);
} }
if words[0].as_str() == "[start_parameters]" {
for i in 0..words.len() { for i in (1..words.len()).step_by(2) {
if i % 2 == 0 {
continue;
}
match words[i].as_str() { match words[i].as_str() {
"decision_variable_count" => { "decision_variable_count" => {
config_file_input.decision_variable_count = words[i + 1].parse().unwrap() config_file_input.decision_variable_count = words[i + 1].parse().unwrap()
@ -105,6 +106,7 @@ impl Input {
_ => {} _ => {}
} }
} }
}
config_file_input config_file_input
} }
@ -114,3 +116,55 @@ impl Input {
input.trim().to_string() input.trim().to_string()
} }
} }
pub fn give_output(best_food_source: FoodSource, run_counter: usize) {
let mut write_file = false;
for arg in args().collect::<Vec<String>>() {
match arg.as_str() {
"-w" | "--write-file" => write_file = true,
_ => {}
}
}
if write_file {
write_output_file(best_food_source, run_counter)
} else {
give_terminal_output(best_food_source, run_counter)
}
}
fn give_terminal_output(best_food_source: FoodSource, run_counter: usize) {
println!("[{}]\n{}\n", run_counter, best_food_source)
}
fn write_output_file(best_food_source: FoodSource, run_counter: usize) {
let mut print_buffer = vec![];
write!(print_buffer, "[{}]\n{}\n", run_counter, best_food_source).unwrap();
let mut file_try_counter = 0;
let file_name = "abc_result";
let file_extension = "toml";
let mut file_path = format!("{}.{}", file_name, file_extension);
let mut file;
if run_counter == 0 {
while File::open(file_path.clone()).is_ok() {
file_try_counter += 1;
file_path = format!("{}{}.{}", file_name, file_try_counter, file_extension);
}
file = File::create_new(file_path).unwrap();
} else {
while File::open(file_path.clone()).is_ok() {
file_try_counter += 1;
file_path = format!("{}{}.{}", file_name, file_try_counter, file_extension);
}
if file_try_counter > 1 {
file_path = format!("{}{}.{}", file_name, file_try_counter - 1, file_extension);
} else {
file_path = format!("{}.{}", file_name, file_extension);
}
file = OpenOptions::new().append(true).open(file_path).unwrap();
}
file.write_all(&print_buffer).unwrap();
file.flush().unwrap();
}

View file

@ -1,4 +1,4 @@
use artificial_bee_colony::{bee::Bee, food::FoodSource, Input}; use artificial_bee_colony::{bee::Bee, food::FoodSource, give_output, Input};
fn main() { fn main() {
println!("Hello, world!"); println!("Hello, world!");
@ -12,11 +12,13 @@ fn main() {
); );
for run_counter in 0..input.run { for run_counter in 0..input.run {
let mut best = FoodSource::get(vec![]); let mut best_food_source = FoodSource::get(vec![]);
for food_source in &food_sources { for food_source in &food_sources {
if best.fitness < food_source.fitness { if best_food_source.fitness < food_source.fitness {
best.coordinates.clone_from(&food_source.coordinates); best_food_source
best.fitness = food_source.fitness; .coordinates
.clone_from(&food_source.coordinates);
best_food_source.fitness = food_source.fitness;
} }
} }
for _ in 0..input.iteration { for _ in 0..input.iteration {
@ -46,7 +48,7 @@ fn main() {
most_tried_index = i; most_tried_index = i;
} }
} }
best = food_sources[most_tried_index].clone(); best_food_source = food_sources[most_tried_index].clone();
Bee::scout_bee( Bee::scout_bee(
&mut food_sources, &mut food_sources,
most_tried_index, most_tried_index,
@ -57,8 +59,6 @@ fn main() {
); );
} }
} }
println!("-------------------------------"); give_output(best_food_source, run_counter)
println!("\n\t|Run {}|\n", run_counter);
println!("{:#?}", best);
} }
} }