Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add WeightedIndexTree to rand_distr #1372

Merged
merged 20 commits into from
Feb 8, 2024
Prev Previous commit
Next Next commit
a
  • Loading branch information
xmakro committed Feb 8, 2024
commit 689ac4875f83d6eb36f0452d63fdbd5a9d429697
31 changes: 13 additions & 18 deletions rand_distr/src/weighted_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,15 @@ use serde::{Deserialize, Serialize};
serde(bound(deserialize = "W: Deserialize<'de>, W::Sampler: Deserialize<'de>"))
)]
#[derive(Clone, Default, Debug, PartialEq)]
pub struct WeightedTreeIndex<W: SampleUniform> {
pub struct WeightedTreeIndex<
W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight,
> {
subtotals: Vec<W>,
}

impl<W: Clone + PartialEq + PartialOrd + SampleUniform + Weight> WeightedTreeIndex<W> {
impl<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight>
WeightedTreeIndex<W>
{
/// Creates a new [`WeightedTreeIndex`] from a slice of weights.
pub fn new<I>(weights: I) -> Result<Self, WeightedError>
where
Expand Down Expand Up @@ -138,28 +142,22 @@ impl<W: Clone + PartialEq + PartialOrd + SampleUniform + Weight> WeightedTreeInd
}

/// Gets the weight at an index.
pub fn get(&self, index: usize) -> W
where
W: for<'a> SubAssign<&'a W>,
{
pub fn get(&self, index: usize) -> W {
let left_index = 2 * index + 1;
let right_index = 2 * index + 2;
let mut w = self.subtotals[index].clone();
w -= &self.subtotal(left_index);
w -= &self.subtotal(right_index);
w -= self.subtotal(left_index);
w -= self.subtotal(right_index);
w
}

/// Removes the last weight and returns it, or [`None`] if it is empty.
pub fn pop(&mut self) -> Option<W>
where
W: for<'a> SubAssign<&'a W>,
{
pub fn pop(&mut self) -> Option<W> {
self.subtotals.pop().map(|weight| {
let mut index = self.len();
while index != 0 {
index = (index - 1) / 2;
self.subtotals[index] -= &weight;
self.subtotals[index] -= weight.clone();
}
weight
})
Expand All @@ -186,15 +184,12 @@ impl<W: Clone + PartialEq + PartialOrd + SampleUniform + Weight> WeightedTreeInd
}

/// Updates the weight at an index.
pub fn update(&mut self, mut index: usize, weight: W) -> Result<(), WeightedError>
where
W: for<'a> SubAssign<&'a W>,
{
pub fn update(&mut self, mut index: usize, weight: W) -> Result<(), WeightedError> {
if weight < W::ZERO {
return Err(WeightedError::InvalidWeight);
}
let mut difference = weight;
difference -= &self.get(index);
difference -= self.get(index);
if difference == W::ZERO {
return Ok(());
}
Expand Down
Loading