use crate::solution::{finalize_scalar_solution, Solution};
use crate::utils::random::{seed_from_time, Random};
pub struct BinarySolutionBuilder {
variables: Vec<bool>,
quality: Option<f64>,
}
impl BinarySolutionBuilder {
pub fn ones(size: usize) -> Self {
Self {
variables: vec![true; size],
quality: None,
}
}
pub fn zeros(size: usize) -> Self {
Self {
variables: vec![false; size],
quality: None,
}
}
pub fn random(size: usize, seed: Option<u64>) -> Self {
let mut rng = if let Some(seed) = seed {
Random::new(seed)
} else {
Random::new(seed_from_time())
};
let variables: Vec<bool> = (0..size).map(|_| rng.coin_flip()).collect();
Self {
variables,
quality: None,
}
}
pub fn from_variables(variables: Vec<bool>) -> Self {
Self {
variables,
quality: None,
}
}
pub fn with_variables(mut self, variables: Vec<bool>) -> Self {
self.variables = variables;
self
}
pub fn with_quality(mut self, quality: f64) -> Self {
self.quality = Some(quality);
self
}
pub fn set_bit(mut self, index: usize) -> Self {
if index < self.variables.len() {
self.variables[index] = true;
}
self
}
pub fn clear_bit(mut self, index: usize) -> Self {
if index < self.variables.len() {
self.variables[index] = false;
}
self
}
pub fn with_pattern(mut self, pattern: &[bool]) -> Self {
let len = self.variables.len().min(pattern.len());
self.variables[..len].copy_from_slice(&pattern[..len]);
self
}
pub fn build(self) -> Solution<bool> {
finalize_scalar_solution(self.variables, self.quality)
}
}
#[cfg(test)]
mod tests {
use crate::solution::implementations::binary_solution::BinarySolutionBuilder;
#[test]
fn test_binary_solution_builder_basic() {
let solution = BinarySolutionBuilder::zeros(5).build();
assert_eq!(solution.num_variables(), 5);
assert_eq!(solution.variables(), &[false, false, false, false, false]);
assert_eq!(solution.quality(), None);
}
#[test]
fn test_binary_solution_builder_with_quality() {
let solution = BinarySolutionBuilder::zeros(3).with_quality(42.5).build();
assert_eq!(solution.quality().copied(), Some(42.5));
}
}