use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::ops::Bound::{Excluded, Unbounded};
use search_core::Cost;
use crate::cost::{Weight, within};
use crate::indexed_heap::IndexedHeap;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum TieBreak {
#[default]
LargerG,
SmallerG,
}
impl TieBreak {
fn cmp_g<C: Cost>(self, a: C, b: C) -> Ordering {
match self {
Self::LargerG => b.cmp(&a),
Self::SmallerG => a.cmp(&b),
}
}
}
#[derive(Debug, Clone, Copy)]
struct OpenKey<C> {
f: C,
g: C,
tie: TieBreak,
seq: u64,
}
impl<C: Cost> PartialEq for OpenKey<C> {
fn eq(&self, other: &Self) -> bool {
self.cmp(other).is_eq()
}
}
impl<C: Cost> Eq for OpenKey<C> {}
impl<C: Cost> PartialOrd for OpenKey<C> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<C: Cost> Ord for OpenKey<C> {
fn cmp(&self, other: &Self) -> Ordering {
self.f
.cmp(&other.f)
.then_with(|| self.tie.cmp_g(self.g, other.g))
.then_with(|| self.seq.cmp(&other.seq))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct FocalOrder<K, O> {
key: K,
open: O,
}
#[derive(Debug, Clone)]
pub struct FocalList<C, K> {
weight: Weight,
tie: TieBreak,
buckets: BTreeMap<C, Vec<usize>>,
boundary: Option<C>,
focal: IndexedHeap<FocalOrder<K, OpenKey<C>>>,
items: Vec<Option<Item<C, K>>>,
len: usize,
pushes: u64,
}
#[derive(Debug, Clone)]
struct Item<C, K> {
open: OpenKey<C>,
key: K,
slot: usize,
}
impl<C: Cost, K: Ord + Clone> FocalList<C, K> {
#[must_use]
pub fn new(weight: Weight) -> Self {
Self::with_tie_break(weight, TieBreak::LargerG)
}
#[must_use]
pub fn with_tie_break(weight: Weight, tie: TieBreak) -> Self {
assert!(
weight.numerator() >= weight.denominator(),
"focal weight must be at least 1"
);
Self {
weight,
tie,
buckets: BTreeMap::new(),
boundary: None,
focal: IndexedHeap::new(),
items: Vec::new(),
len: 0,
pushes: 0,
}
}
#[must_use]
pub fn len(&self) -> usize {
self.len
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[must_use]
pub fn focal_len(&self) -> usize {
self.focal.len()
}
#[must_use]
pub fn contains(&self, item: usize) -> bool {
self.item(item).is_some()
}
#[must_use]
pub fn f(&self, item: usize) -> Option<C> {
self.item(item).map(|entry| entry.open.f)
}
#[must_use]
pub fn min_f(&self) -> Option<C> {
self.buckets.first_key_value().map(|(&f, _)| f)
}
#[must_use]
pub fn peek_min_f(&self) -> Option<usize> {
let (_, bucket) = self.buckets.first_key_value()?;
bucket
.iter()
.filter_map(|&item| self.item(item).map(|entry| (entry.open, item)))
.min()
.map(|(_, item)| item)
}
#[must_use]
pub fn peek(&self) -> Option<usize> {
self.focal.peek().map(|(_, item)| item)
}
pub fn pop(&mut self) -> Option<usize> {
let item = self.peek()?;
self.remove(item);
Some(item)
}
pub fn push(&mut self, item: usize, f: C, g: C, key: K) {
self.detach(item);
let open = OpenKey {
f,
g,
tie: self.tie,
seq: self.pushes,
};
self.pushes += 1;
self.len += 1;
let bucket = self.buckets.entry(f).or_default();
let slot = bucket.len();
bucket.push(item);
if self.is_focal(f) {
self.focal.insert(
item,
FocalOrder {
key: key.clone(),
open,
},
);
}
if self.items.len() <= item {
self.items.resize_with(item + 1, || None);
}
self.items[item] = Some(Item { open, key, slot });
self.rebalance();
}
pub fn remove(&mut self, item: usize) -> bool {
let present = self.detach(item);
if present {
self.rebalance();
}
present
}
fn item(&self, item: usize) -> Option<&Item<C, K>> {
self.items.get(item).and_then(Option::as_ref)
}
fn is_focal(&self, f: C) -> bool {
self.boundary.is_some_and(|boundary| f <= boundary)
}
fn detach(&mut self, item: usize) -> bool {
let Some(entry) = self.items.get_mut(item).and_then(Option::take) else {
return false;
};
let f = entry.open.f;
if self.is_focal(f) {
self.focal.remove(item);
}
self.len -= 1;
self.unbucket(f, entry.slot);
true
}
fn unbucket(&mut self, f: C, slot: usize) {
let bucket = self.buckets.get_mut(&f).expect("every item has a bucket");
bucket.swap_remove(slot);
if let Some(&moved) = bucket.get(slot) {
self.items[moved]
.as_mut()
.expect("every bucketed item is in the list")
.slot = slot;
}
if bucket.is_empty() {
self.buckets.remove(&f);
if self.boundary == Some(f) {
self.boundary = self.buckets.range(..f).next_back().map(|(&f, _)| f);
}
}
}
fn rebalance(&mut self) {
let Some(min_f) = self.min_f() else {
self.boundary = None;
return;
};
while let Some(boundary) = self.boundary {
if within(boundary, self.weight, min_f) {
break;
}
self.leave_focal(boundary);
self.boundary = self.buckets.range(..boundary).next_back().map(|(&f, _)| f);
}
loop {
let next = match self.boundary {
Some(boundary) => self.buckets.range((Excluded(boundary), Unbounded)).next(),
None => self.buckets.first_key_value(),
};
let Some(f) = next
.map(|(&f, _)| f)
.filter(|&f| within(f, self.weight, min_f))
else {
break;
};
self.enter_focal(f);
self.boundary = Some(f);
}
}
fn enter_focal(&mut self, f: C) {
for &item in &self.buckets[&f] {
let entry = self.items[item]
.as_ref()
.expect("every bucketed item is in the list");
let order = FocalOrder {
key: entry.key.clone(),
open: entry.open,
};
self.focal.insert(item, order);
}
}
fn leave_focal(&mut self, f: C) {
for &item in &self.buckets[&f] {
self.focal.remove(item);
}
}
}
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use proptest::prelude::*;
use super::{FocalList, TieBreak};
use crate::cost::{Weight, within};
#[derive(Debug, Clone)]
enum Op {
Push(usize, u32, u32, u8),
Remove(usize),
Pop,
}
fn ops() -> impl Strategy<Value = Vec<Op>> {
let op = prop_oneof![
(0_usize..8, 0_u32..30, 0_u32..10, 0_u8..4)
.prop_map(|(i, f, g, k)| Op::Push(i, f, g, k)),
(0_usize..8).prop_map(Op::Remove),
Just(Op::Pop),
];
prop::collection::vec(op, 0..60)
}
proptest! {
#[test]
fn matches_naive_model(ops in ops(), numerator in 2_u32..6, larger_g in any::<bool>()) {
let weight = Weight::new(numerator, 2);
let tie = if larger_g { TieBreak::LargerG } else { TieBreak::SmallerG };
let mut list = FocalList::with_tie_break(weight, tie);
let mut model: Vec<(usize, u32, u32, u8, usize)> = Vec::new();
for (seq, op) in ops.into_iter().enumerate() {
let min_f = model.iter().map(|e| e.1).min();
let best = min_f.and_then(|min_f| {
model
.iter()
.filter(|e| within(e.1, weight, min_f))
.min_by_key(|e| (e.3, e.1, if larger_g { u32::MAX - e.2 } else { e.2 }, e.4))
.map(|e| e.0)
});
match op {
Op::Push(item, f, g, key) => {
model.retain(|e| e.0 != item);
model.push((item, f, g, key, seq));
list.push(item, f, g, key);
}
Op::Remove(item) => {
let present = model.iter().any(|e| e.0 == item);
model.retain(|e| e.0 != item);
prop_assert_eq!(list.remove(item), present);
}
Op::Pop => {
prop_assert_eq!(list.pop(), best);
model.retain(|e| Some(e.0) != best);
}
}
let min_f = model.iter().map(|e| e.1).min();
let focal = min_f.map_or(0, |min_f| model.iter().filter(|e| within(e.1, weight, min_f)).count());
prop_assert_eq!(list.len(), model.len());
prop_assert_eq!(list.focal_len(), focal);
prop_assert_eq!(list.min_f(), min_f);
let first = model
.iter()
.min_by_key(|e| (e.1, if larger_g { u32::MAX - e.2 } else { e.2 }, e.4))
.map(|e| e.0);
prop_assert_eq!(list.peek_min_f(), first);
}
}
}
}