rust_dsa

Struct GenericFenwickTree

Source
pub struct GenericFenwickTree<T, F> { /* private fields */ }
Expand description

A Fenwick tree that is generic over any type T and associative function F.

A Fenwick tree behaves more or less like a Vec<T>. Values can be pushed, popped and indexed as usual. But Fenwick trees are equipped with an addition operation that calculates prefix sums in O(log n) time. Note that “sum” is used in the documentation because addition is the most common operation, but any associative operation with an identity (any monoid) works.

For all values a, b and c, f and id should obey the following properties:

f(f(a, b), c) == f(a, f(b, c))
f(id, a) == a == f(a, id)

See also: FenwickTree.

§Example

use rust_dsa::GenericFenwickTree;

// First, we create a new tree.
let mut tree = GenericFenwickTree::new(0, |&a, &b| a + b);

// Then we push some values.
tree.push(1);
tree.push(4);
tree.push(3);
tree.push(-2);

// We can index into the tree.
assert_eq!(tree[1], 4);
assert_eq!(tree.get(2), Some(&3));
assert_eq!(tree.get(4), None);

// And we can calculate prefix sums.
assert_eq!(tree.sum_to(2), 5);
assert_eq!(tree.sum_to(3), 8);
assert_eq!(tree.total(), 6);

// We can also pop values.
assert_eq!(tree.pop(), Some(-2));
assert_eq!(tree.pop(), Some(3));

// Fenwick trees work with any associative function.
let mut strings = GenericFenwickTree::new(
    String::new(),
    |a, b| format!("{a}{b}"),
);
strings.push("foo".into());
strings.push("bar".into());
strings.push("baz".into());

assert_eq!(strings.sum_to(2), "foobar");

// We can also create them direcly from arrays.
let prod = GenericFenwickTree::from_array(
    1,
    |&a, &b| a * b,
    [1, 2, 3, 4, 5, 6],
);

assert_eq!(prod.sum_to(4), 24);
assert_eq!(prod.total(), 720);

§Runtime complexity

Implementations§

Source§

impl<T, F> GenericFenwickTree<T, F>
where F: Fn(&T, &T) -> T,

Source

pub fn new(id: T, f: F) -> Self

Creates a Fenwick tree.

Source

pub fn from_array<const N: usize>(id: T, f: F, array: [T; N]) -> Self

Creates a Fenwick tree from an array in linear time.

§Example
use rust_dsa::GenericFenwickTree;

let tree = GenericFenwickTree::from_array(
    String::new(),
    |a, b| format!("{a}{b}"),
    [
        "foo".into(),
        "bar".into(),
        "b".into(),
        "az".into(),
        "!".into(),
    ],
);

assert_eq!(tree.total(), "foobarbaz!");
assert_eq!(tree.sum_to(2), "foobar");
Source

pub fn push(&mut self, value: T)

Pushes a value onto the end of the tree.

§Example
use rust_dsa::GenericFenwickTree;

let mut tree = GenericFenwickTree::new(0, |&a, &b| a + b);
tree.push(1);
tree.push(4);
tree.push(3);
tree.push(-1);

assert_eq!(tree.len(), 4);
assert_eq!(tree.get(1), Some(&4));
assert_eq!(tree.total(), 7);
Source

pub fn get(&self, index: usize) -> Option<&T>

Returns a reference to the value at position index if one exists.

§Example
use rust_dsa::GenericFenwickTree;

let tree = GenericFenwickTree::from_array(
    0,
    |&a, &b| a + b,
    [8, 4, 2],
);

assert_eq!(tree.get(1), Some(&4));
assert_eq!(tree.get(6), None);
Source

pub fn pop(&mut self) -> Option<T>

Removes and returns the last value in the tree, or None if the tree is empty.

§Example
use rust_dsa::GenericFenwickTree;

let mut tree = GenericFenwickTree::from_array(
    0,
    |&a, &b| a + b,
    [8, 4, 2],
);

assert_eq!(tree.pop(), Some(2));
assert_eq!(tree.pop(), Some(4));
assert_eq!(tree.pop(), Some(8));
assert_eq!(tree.pop(), None);
Source

pub fn last(&self) -> Option<&T>

Returns a reference to the last value in the tree, or None if the tree is empty.

§Example
use rust_dsa::GenericFenwickTree;

let tree = GenericFenwickTree::from_array(
    0,
    |&a, &b| a + b,
    [8, 4, 2],
);

assert_eq!(tree.last(), Some(&2));
Source

pub fn sum_to(&self, end: usize) -> T

Returns the associative operation f applied to the values with indices in the range [0, end).

§Panics

Panics if end is larger than the number of values in the tree.

§Example
use rust_dsa::GenericFenwickTree;

let tree = GenericFenwickTree::from_array(
    1,
    |&a, &b| a * b,
    [1, 2, 3, 4, 5],
);

assert_eq!(tree.sum_to(0), 1);
assert_eq!(tree.sum_to(3), 6);
assert_eq!(tree.sum_to(5), 120);
Source

pub fn total(&self) -> T

Returns the associative operation f applied to all values in the tree.

§Example
use rust_dsa::GenericFenwickTree;

let tree = GenericFenwickTree::from_array(
    Vec::new(),
    |a, b| [a.clone(), b.clone()].concat(),
    [
        vec![1, 2, 3],
        vec![-2, -1],
        vec![8],
    ],
);

assert_eq!(tree.total(), vec![1, 2, 3, -2, -1, 8]);
Source

pub fn update(&mut self, index: usize, delta: &T)

Updates the value at index.

§Panics

Panics if index is out of bounds.

§Example
use rust_dsa::GenericFenwickTree;

let mut tree = GenericFenwickTree::new(
    0,
    |&a, &b| a + b
);
tree.push(1);
tree.push(4);
tree.push(2);

assert_eq!(tree.total(), 7);

tree.update(0, &2);
tree.update(1, &-1);

assert_eq!(tree[0], 3);
assert_eq!(tree[1], 3);
assert_eq!(tree.total(), 8);
Source

pub fn len(&self) -> usize

Returns the number of values in the tree.

§Example
use rust_dsa::GenericFenwickTree;

let mut tree = GenericFenwickTree::new(0.0, |&a, &b| a + b);

assert_eq!(tree.len(), 0);

tree.push(1.5);

assert_eq!(tree.len(), 1);
Source

pub fn is_empty(&self) -> bool

Returns true if the tree is empty.

§Example
use rust_dsa::GenericFenwickTree;

let mut tree = GenericFenwickTree::new(0.0, |&a, &b| a + b);

assert!(tree.is_empty());

tree.push(4.2);

assert!(!tree.is_empty());
Source

pub fn clear(&mut self)

Empties the tree.

§Example
use rust_dsa::GenericFenwickTree;

let mut tree = GenericFenwickTree::from_array(
    1,
    |&a, &b| a * b,
    [1, 2, 3, 4, 5],
);

assert!(!tree.is_empty());

tree.clear();

assert!(tree.is_empty());

Trait Implementations§

Source§

impl<T: Clone, F: Clone> Clone for GenericFenwickTree<T, F>

Source§

fn clone(&self) -> GenericFenwickTree<T, F>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T, F> Index<usize> for GenericFenwickTree<T, F>

Source§

type Output = T

The returned type after indexing.
Source§

fn index(&self, index: usize) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl<'a, T, F> IntoIterator for &'a GenericFenwickTree<T, F>

Source§

type Item = &'a T

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T, F> IntoIterator for GenericFenwickTree<T, F>

Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<T, F> Freeze for GenericFenwickTree<T, F>
where T: Freeze, F: Freeze,

§

impl<T, F> RefUnwindSafe for GenericFenwickTree<T, F>

§

impl<T, F> Send for GenericFenwickTree<T, F>
where T: Send, F: Send,

§

impl<T, F> Sync for GenericFenwickTree<T, F>
where T: Sync, F: Sync,

§

impl<T, F> Unpin for GenericFenwickTree<T, F>
where T: Unpin, F: Unpin,

§

impl<T, F> UnwindSafe for GenericFenwickTree<T, F>
where T: UnwindSafe, F: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.