use alloc::vec::Vec;
use core::cmp::Ordering;
#[must_use]
pub fn sanitize(cost: f64) -> f64 {
if cost.is_nan() { f64::INFINITY } else { cost }
}
#[derive(Debug, Clone, PartialEq)]
pub struct Individual<G> {
pub genome: G,
pub cost: f64,
}
impl<G> Individual<G> {
#[must_use]
pub fn new(genome: G, cost: f64) -> Self {
Self {
genome,
cost: sanitize(cost),
}
}
}
pub(crate) fn compare(a: f64, b: f64) -> Ordering {
a.total_cmp(&b)
}
#[must_use]
pub fn ranking(costs: &[f64]) -> Vec<usize> {
let mut order: Vec<usize> = (0..costs.len()).collect();
order.sort_by(|&a, &b| compare(costs[a], costs[b]).then(a.cmp(&b)));
order
}
pub(crate) fn sort_population<G>(population: &mut [Individual<G>]) {
population.sort_by(|a, b| compare(a.cost, b.cost));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ranking_is_stable_and_nan_last() {
let costs = [2.0, 1.0, sanitize(f64::NAN), 1.0, -0.0];
assert_eq!(ranking(&costs), [4, 1, 3, 0, 2]);
}
}