repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/selection_sort.rs | src/sorting/selection_sort.rs | pub fn selection_sort<T: Ord>(arr: &mut [T]) {
let len = arr.len();
for left in 0..len {
let mut smallest = left;
for right in (left + 1)..len {
if arr[right] < arr[smallest] {
smallest = right;
}
}
arr.swap(smallest, left);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn basic() {
let mut res = vec!["d", "a", "c", "b"];
let cloned = res.clone();
selection_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn empty() {
let mut res = Vec::<u8>::new();
let cloned = res.clone();
selection_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn one_element() {
let mut res = vec!["a"];
let cloned = res.clone();
selection_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn pre_sorted() {
let mut res = vec!["a", "b", "c"];
let cloned = res.clone();
selection_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/dutch_national_flag_sort.rs | src/sorting/dutch_national_flag_sort.rs | /*
A Rust implementation of the Dutch National Flag sorting algorithm.
Reference implementation: https://github.com/TheAlgorithms/Python/blob/master/sorts/dutch_national_flag_sort.py
More info: https://en.wikipedia.org/wiki/Dutch_national_flag_problem
*/
#[derive(PartialOrd, PartialEq, Eq)]
pub enum Colors {
Red, // \
White, // | Define the three colors of the Dutch Flag: 🇳🇱
Blue, // /
}
use Colors::{Blue, Red, White};
// Algorithm implementation
pub fn dutch_national_flag_sort(mut sequence: Vec<Colors>) -> Vec<Colors> {
// We take ownership of `sequence` because the original `sequence` will be modified and then returned
let length = sequence.len();
if length <= 1 {
return sequence; // Arrays of length 0 or 1 are automatically sorted
}
let mut low = 0;
let mut mid = 0;
let mut high = length - 1;
while mid <= high {
match sequence[mid] {
Red => {
sequence.swap(low, mid);
low += 1;
mid += 1;
}
White => {
mid += 1;
}
Blue => {
sequence.swap(mid, high);
high -= 1;
}
}
}
sequence
}
#[cfg(test)]
mod tests {
use super::super::is_sorted;
use super::*;
#[test]
fn random_array() {
let arr = vec![
Red, Blue, White, White, Blue, Blue, Red, Red, White, Blue, White, Red, White, Blue,
];
let arr = dutch_national_flag_sort(arr);
assert!(is_sorted(&arr))
}
#[test]
fn sorted_array() {
let arr = vec![
Red, Red, Red, Red, Red, White, White, White, White, White, Blue, Blue, Blue, Blue,
];
let arr = dutch_national_flag_sort(arr);
assert!(is_sorted(&arr))
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/counting_sort.rs | src/sorting/counting_sort.rs | /// In place counting sort for collections of u32
/// O(n + maxval) in time, where maxval is the biggest value an input can possibly take
/// O(maxval) in memory
/// u32 is chosen arbitrarly, a counting sort probably should'nt be used on data that requires bigger types.
pub fn counting_sort(arr: &mut [u32], maxval: usize) {
let mut occurences: Vec<usize> = vec![0; maxval + 1];
for &data in arr.iter() {
occurences[data as usize] += 1;
}
let mut i = 0;
for (data, &number) in occurences.iter().enumerate() {
for _ in 0..number {
arr[i] = data as u32;
i += 1;
}
}
}
use std::ops::AddAssign;
/// Generic implementation of a counting sort for all usigned types
pub fn generic_counting_sort<T: Into<u64> + From<u8> + AddAssign + Copy>(
arr: &mut [T],
maxval: usize,
) {
let mut occurences: Vec<usize> = vec![0; maxval + 1];
for &data in arr.iter() {
occurences[data.into() as usize] += 1;
}
// Current index in output array
let mut i = 0;
// current data point, necessary to be type-safe
let mut data = T::from(0);
// This will iterate from 0 to the largest data point in `arr`
// `number` contains the occurances of the data point `data`
for &number in occurences.iter() {
for _ in 0..number {
arr[i] = data;
i += 1;
}
data += T::from(1);
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn counting_sort_descending() {
let mut ve1 = vec![6, 5, 4, 3, 2, 1];
let cloned = ve1.clone();
counting_sort(&mut ve1, 6);
assert!(is_sorted(&ve1) && have_same_elements(&ve1, &cloned));
}
#[test]
fn counting_sort_pre_sorted() {
let mut ve2 = vec![1, 2, 3, 4, 5, 6];
let cloned = ve2.clone();
counting_sort(&mut ve2, 6);
assert!(is_sorted(&ve2) && have_same_elements(&ve2, &cloned));
}
#[test]
fn generic_counting_sort() {
let mut ve1: Vec<u8> = vec![100, 30, 60, 10, 20, 120, 1];
let cloned = ve1.clone();
super::generic_counting_sort(&mut ve1, 120);
assert!(is_sorted(&ve1) && have_same_elements(&ve1, &cloned));
}
#[test]
fn presorted_u64_counting_sort() {
let mut ve2: Vec<u64> = vec![1, 2, 3, 4, 5, 6];
let cloned = ve2.clone();
super::generic_counting_sort(&mut ve2, 6);
assert!(is_sorted(&ve2) && have_same_elements(&ve2, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/radix_sort.rs | src/sorting/radix_sort.rs | /// Sorts the elements of `arr` in-place using radix sort.
///
/// Time complexity is `O((n + b) * logb(k))`, where `n` is the number of elements,
/// `b` is the base (the radix), and `k` is the largest element.
/// When `n` and `b` are roughly the same maginitude, this algorithm runs in linear time.
///
/// Space complexity is `O(n + b)`.
pub fn radix_sort(arr: &mut [u64]) {
let max: usize = match arr.iter().max() {
Some(&x) => x as usize,
None => return,
};
// Make radix a power of 2 close to arr.len() for optimal runtime
let radix = arr.len().next_power_of_two();
// Counting sort by each digit from least to most significant
let mut place = 1;
while place <= max {
let digit_of = |x| x as usize / place % radix;
// Count digit occurrences
let mut counter = vec![0; radix];
for &x in arr.iter() {
counter[digit_of(x)] += 1;
}
// Compute last index of each digit
for i in 1..radix {
counter[i] += counter[i - 1];
}
// Write elements to their new indices
for &x in arr.to_owned().iter().rev() {
counter[digit_of(x)] -= 1;
arr[counter[digit_of(x)]] = x;
}
place *= radix;
}
}
#[cfg(test)]
mod tests {
use super::radix_sort;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn empty() {
let mut a: [u64; 0] = [];
let cloned = a;
radix_sort(&mut a);
assert!(is_sorted(&a) && have_same_elements(&a, &cloned));
}
#[test]
fn descending() {
let mut v = vec![201, 127, 64, 37, 24, 4, 1];
let cloned = v.clone();
radix_sort(&mut v);
assert!(is_sorted(&v) && have_same_elements(&v, &cloned));
}
#[test]
fn ascending() {
let mut v = vec![1, 4, 24, 37, 64, 127, 201];
let cloned = v.clone();
radix_sort(&mut v);
assert!(is_sorted(&v) && have_same_elements(&v, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/wave_sort.rs | src/sorting/wave_sort.rs | /// Wave Sort Algorithm
///
/// Wave Sort is a sorting algorithm that works in O(n log n) time assuming
/// the sort function used works in O(n log n) time.
/// It arranges elements in an array into a sequence where every alternate
/// element is either greater or smaller than its adjacent elements.
///
/// Reference:
/// [Wave Sort Algorithm - GeeksforGeeks](https://www.geeksforgeeks.org/sort-array-wave-form-2/)
///
/// # Examples
///
/// use the_algorithms_rust::sorting::wave_sort;
/// let array = vec![10, 90, 49, 2, 1, 5, 23];
/// let result = wave_sort(array);
/// // Result: [2, 1, 10, 5, 49, 23, 90]
///
pub fn wave_sort<T: Ord>(arr: &mut [T]) {
let n = arr.len();
arr.sort();
for i in (0..n - 1).step_by(2) {
arr.swap(i, i + 1);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_case_1() {
let mut array = vec![10, 90, 49, 2, 1, 5, 23];
wave_sort(&mut array);
let expected = vec![2, 1, 10, 5, 49, 23, 90];
assert_eq!(&array, &expected);
}
#[test]
fn test_case_2() {
let mut array = vec![1, 3, 4, 2, 7, 8];
wave_sort(&mut array);
let expected = vec![2, 1, 4, 3, 8, 7];
assert_eq!(&array, &expected);
}
#[test]
fn test_case_3() {
let mut array = vec![3, 3, 3, 3];
wave_sort(&mut array);
let expected = vec![3, 3, 3, 3];
assert_eq!(&array, &expected);
}
#[test]
fn test_case_4() {
let mut array = vec![9, 4, 6, 8, 14, 3];
wave_sort(&mut array);
let expected = vec![4, 3, 8, 6, 14, 9];
assert_eq!(&array, &expected);
}
#[test]
fn test_case_5() {
let mut array = vec![5, 10, 15, 20, 25];
wave_sort(&mut array);
let expected = vec![10, 5, 20, 15, 25];
assert_eq!(&array, &expected);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/stooge_sort.rs | src/sorting/stooge_sort.rs | fn _stooge_sort<T: Ord>(arr: &mut [T], start: usize, end: usize) {
if arr[start] > arr[end] {
arr.swap(start, end);
}
if start + 1 >= end {
return;
}
let k = (end - start + 1) / 3;
_stooge_sort(arr, start, end - k);
_stooge_sort(arr, start + k, end);
_stooge_sort(arr, start, end - k);
}
pub fn stooge_sort<T: Ord>(arr: &mut [T]) {
let len = arr.len();
if len == 0 {
return;
}
_stooge_sort(arr, 0, len - 1);
}
#[cfg(test)]
mod test {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn basic() {
let mut vec = vec![3, 5, 6, 3, 1, 4];
let cloned = vec.clone();
stooge_sort(&mut vec);
assert!(is_sorted(&vec) && have_same_elements(&vec, &cloned));
}
#[test]
fn empty() {
let mut vec: Vec<i32> = vec![];
let cloned = vec.clone();
stooge_sort(&mut vec);
assert!(is_sorted(&vec) && have_same_elements(&vec, &cloned));
}
#[test]
fn reverse() {
let mut vec = vec![6, 5, 4, 3, 2, 1];
let cloned = vec.clone();
stooge_sort(&mut vec);
assert!(is_sorted(&vec) && have_same_elements(&vec, &cloned));
}
#[test]
fn already_sorted() {
let mut vec = vec![1, 2, 3, 4, 5, 6];
let cloned = vec.clone();
stooge_sort(&mut vec);
assert!(is_sorted(&vec) && have_same_elements(&vec, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/bead_sort.rs | src/sorting/bead_sort.rs | //Bead sort only works for sequences of non-negative integers.
//https://en.wikipedia.org/wiki/Bead_sort
pub fn bead_sort(a: &mut [usize]) {
// Find the maximum element
let mut max = a[0];
(1..a.len()).for_each(|i| {
if a[i] > max {
max = a[i];
}
});
// allocating memory
let mut beads = vec![vec![0; max]; a.len()];
// mark the beads
for i in 0..a.len() {
for j in (0..a[i]).rev() {
beads[i][j] = 1;
}
}
// move down the beads
for j in 0..max {
let mut sum = 0;
(0..a.len()).for_each(|i| {
sum += beads[i][j];
beads[i][j] = 0;
});
for k in ((a.len() - sum)..a.len()).rev() {
a[k] = j + 1;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn descending() {
//descending
let mut ve1: [usize; 5] = [5, 4, 3, 2, 1];
let cloned = ve1;
bead_sort(&mut ve1);
assert!(is_sorted(&ve1) && have_same_elements(&ve1, &cloned));
}
#[test]
fn mix_values() {
//pre-sorted
let mut ve2: [usize; 5] = [7, 9, 6, 2, 3];
let cloned = ve2;
bead_sort(&mut ve2);
assert!(is_sorted(&ve2) && have_same_elements(&ve2, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/bogo_sort.rs | src/sorting/bogo_sort.rs | use crate::math::PCG32;
use std::time::{SystemTime, UNIX_EPOCH};
const DEFAULT: u64 = 4294967296;
fn is_sorted<T: Ord>(arr: &[T], len: usize) -> bool {
for i in 0..len - 1 {
if arr[i] > arr[i + 1] {
return false;
}
}
true
}
#[cfg(target_pointer_width = "64")]
fn generate_index(range: usize, generator: &mut PCG32) -> usize {
generator.get_u64() as usize % range
}
#[cfg(not(target_pointer_width = "64"))]
fn generate_index(range: usize, generator: &mut PCG32) -> usize {
generator.get_u32() as usize % range
}
/**
* Fisher–Yates shuffle for generating random permutation.
*/
fn permute_randomly<T>(arr: &mut [T], len: usize, generator: &mut PCG32) {
for i in (1..len).rev() {
let j = generate_index(i + 1, generator);
arr.swap(i, j);
}
}
pub fn bogo_sort<T: Ord>(arr: &mut [T]) {
let seed = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(duration) => duration.as_millis() as u64,
Err(_) => DEFAULT,
};
let mut random_generator = PCG32::new_default(seed);
let arr_length = arr.len();
while !is_sorted(arr, arr_length) {
permute_randomly(arr, arr_length, &mut random_generator);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn random_array() {
let mut arr = [1, 8, 3, 2, 7, 4, 6, 5];
bogo_sort(&mut arr);
for i in 0..arr.len() - 1 {
assert!(arr[i] <= arr[i + 1]);
}
}
#[test]
fn sorted_array() {
let mut arr = [1, 2, 3, 4, 5, 6, 7, 8];
bogo_sort(&mut arr);
for i in 0..arr.len() - 1 {
assert!(arr[i] <= arr[i + 1]);
}
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/gnome_sort.rs | src/sorting/gnome_sort.rs | use std::cmp;
pub fn gnome_sort<T>(arr: &[T]) -> Vec<T>
where
T: cmp::PartialEq + cmp::PartialOrd + Clone,
{
let mut arr = arr.to_vec();
let mut i: usize = 1;
let mut j: usize = 2;
while i < arr.len() {
if arr[i - 1] < arr[i] {
i = j;
j = i + 1;
} else {
arr.swap(i - 1, i);
i -= 1;
if i == 0 {
i = j;
j += 1;
}
}
}
arr
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn basic() {
let original = [6, 5, -8, 3, 2, 3];
let res = gnome_sort(&original);
assert!(is_sorted(&res) && have_same_elements(&res, &original));
}
#[test]
fn already_sorted() {
let original = gnome_sort(&["a", "b", "c"]);
let res = gnome_sort(&original);
assert!(is_sorted(&res) && have_same_elements(&res, &original));
}
#[test]
fn odd_number_of_elements() {
let original = gnome_sort(&["d", "a", "c", "e", "b"]);
let res = gnome_sort(&original);
assert!(is_sorted(&res) && have_same_elements(&res, &original));
}
#[test]
fn one_element() {
let original = gnome_sort(&[3]);
let res = gnome_sort(&original);
assert!(is_sorted(&res) && have_same_elements(&res, &original));
}
#[test]
fn empty() {
let original = gnome_sort(&Vec::<u8>::new());
let res = gnome_sort(&original);
assert!(is_sorted(&res) && have_same_elements(&res, &original));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/sleep_sort.rs | src/sorting/sleep_sort.rs | use std::sync::mpsc;
use std::thread;
use std::time::Duration;
pub fn sleep_sort(vec: &[usize]) -> Vec<usize> {
let len = vec.len();
let (tx, rx) = mpsc::channel();
for &x in vec.iter() {
let tx: mpsc::Sender<usize> = tx.clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis((20 * x) as u64));
tx.send(x).expect("panic");
});
}
let mut sorted_list: Vec<usize> = Vec::new();
for _ in 0..len {
sorted_list.push(rx.recv().unwrap())
}
sorted_list
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let res = sleep_sort(&[]);
assert_eq!(res, &[]);
}
#[test]
fn single_element() {
let res = sleep_sort(&[1]);
assert_eq!(res, &[1]);
}
#[test]
fn sorted_array() {
let res = sleep_sort(&[1, 2, 3, 4]);
assert_eq!(res, &[1, 2, 3, 4]);
}
#[test]
fn unsorted_array() {
let res = sleep_sort(&[3, 4, 2, 1]);
assert_eq!(res, &[1, 2, 3, 4]);
}
#[test]
fn odd_number_of_elements() {
let res = sleep_sort(&[3, 1, 7]);
assert_eq!(res, &[1, 3, 7]);
}
#[test]
fn repeated_elements() {
let res = sleep_sort(&[1, 1, 1, 1]);
assert_eq!(res, &[1, 1, 1, 1]);
}
#[test]
fn random_elements() {
let res = sleep_sort(&[5, 3, 7, 10, 1, 0, 8]);
assert_eq!(res, &[0, 1, 3, 5, 7, 8, 10]);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/tree_sort.rs | src/sorting/tree_sort.rs | // Author : cyrixninja
// Tree Sort Algorithm
// https://en.wikipedia.org/wiki/Tree_sort
// Wikipedia :A tree sort is a sort algorithm that builds a binary search tree from the elements to be sorted, and then traverses the tree (in-order) so that the elements come out in sorted order.
// Its typical use is sorting elements online: after each insertion, the set of elements seen so far is available in sorted order.
struct TreeNode<T> {
value: T,
left: Option<Box<TreeNode<T>>>,
right: Option<Box<TreeNode<T>>>,
}
impl<T> TreeNode<T> {
fn new(value: T) -> Self {
TreeNode {
value,
left: None,
right: None,
}
}
}
struct BinarySearchTree<T> {
root: Option<Box<TreeNode<T>>>,
}
impl<T: Ord + Clone> BinarySearchTree<T> {
fn new() -> Self {
BinarySearchTree { root: None }
}
fn insert(&mut self, value: T) {
self.root = Some(Self::insert_recursive(self.root.take(), value));
}
fn insert_recursive(root: Option<Box<TreeNode<T>>>, value: T) -> Box<TreeNode<T>> {
match root {
None => Box::new(TreeNode::new(value)),
Some(mut node) => {
if value <= node.value {
node.left = Some(Self::insert_recursive(node.left.take(), value));
} else {
node.right = Some(Self::insert_recursive(node.right.take(), value));
}
node
}
}
}
fn in_order_traversal(&self, result: &mut Vec<T>) {
Self::in_order_recursive(&self.root, result);
}
fn in_order_recursive(root: &Option<Box<TreeNode<T>>>, result: &mut Vec<T>) {
if let Some(node) = root {
Self::in_order_recursive(&node.left, result);
result.push(node.value.clone());
Self::in_order_recursive(&node.right, result);
}
}
}
pub fn tree_sort<T: Ord + Clone>(arr: &mut Vec<T>) {
let mut tree = BinarySearchTree::new();
for elem in arr.iter().cloned() {
tree.insert(elem);
}
let mut result = Vec::new();
tree.in_order_traversal(&mut result);
*arr = result;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_empty_array() {
let mut arr: Vec<i32> = vec![];
tree_sort(&mut arr);
assert_eq!(arr, vec![]);
}
#[test]
fn test_single_element() {
let mut arr = vec![8];
tree_sort(&mut arr);
assert_eq!(arr, vec![8]);
}
#[test]
fn test_already_sorted() {
let mut arr = vec![1, 2, 3, 4, 5];
tree_sort(&mut arr);
assert_eq!(arr, vec![1, 2, 3, 4, 5]);
}
#[test]
fn test_reverse_sorted() {
let mut arr = vec![5, 4, 3, 2, 1];
tree_sort(&mut arr);
assert_eq!(arr, vec![1, 2, 3, 4, 5]);
}
#[test]
fn test_random() {
let mut arr = vec![9, 6, 10, 11, 2, 19];
tree_sort(&mut arr);
assert_eq!(arr, vec![2, 6, 9, 10, 11, 19]);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/bubble_sort.rs | src/sorting/bubble_sort.rs | pub fn bubble_sort<T: Ord>(arr: &mut [T]) {
if arr.is_empty() {
return;
}
let mut sorted = false;
let mut n = arr.len();
while !sorted {
sorted = true;
for i in 0..n - 1 {
if arr[i] > arr[i + 1] {
arr.swap(i, i + 1);
sorted = false;
}
}
n -= 1;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn descending() {
//descending
let mut ve1 = vec![6, 5, 4, 3, 2, 1];
let cloned = ve1.clone();
bubble_sort(&mut ve1);
assert!(is_sorted(&ve1) && have_same_elements(&ve1, &cloned));
}
#[test]
fn ascending() {
//pre-sorted
let mut ve2 = vec![1, 2, 3, 4, 5, 6];
let cloned = ve2.clone();
bubble_sort(&mut ve2);
assert!(is_sorted(&ve2) && have_same_elements(&ve2, &cloned));
}
#[test]
fn empty() {
let mut ve3: Vec<usize> = vec![];
let cloned = ve3.clone();
bubble_sort(&mut ve3);
assert!(is_sorted(&ve3) && have_same_elements(&ve3, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/tim_sort.rs | src/sorting/tim_sort.rs | //! Implements Tim sort algorithm.
//!
//! Tim sort is a hybrid sorting algorithm derived from merge sort and insertion sort.
//! It is designed to perform well on many kinds of real-world data.
use crate::sorting::insertion_sort;
use std::cmp;
static MIN_MERGE: usize = 32;
/// Calculates the minimum run length for Tim sort based on the length of the array.
///
/// The minimum run length is determined using a heuristic that ensures good performance.
///
/// # Arguments
///
/// * `array_length` - The length of the array.
///
/// # Returns
///
/// The minimum run length.
fn compute_min_run_length(array_length: usize) -> usize {
let mut remaining_length = array_length;
let mut result = 0;
while remaining_length >= MIN_MERGE {
result |= remaining_length & 1;
remaining_length >>= 1;
}
remaining_length + result
}
/// Merges two sorted subarrays into a single sorted subarray.
///
/// This function merges two sorted subarrays of the provided slice into a single sorted subarray.
///
/// # Arguments
///
/// * `arr` - The slice containing the subarrays to be merged.
/// * `left` - The starting index of the first subarray.
/// * `mid` - The ending index of the first subarray.
/// * `right` - The ending index of the second subarray.
fn merge<T: Ord + Copy>(arr: &mut [T], left: usize, mid: usize, right: usize) {
let left_slice = arr[left..=mid].to_vec();
let right_slice = arr[mid + 1..=right].to_vec();
let mut i = 0;
let mut j = 0;
let mut k = left;
while i < left_slice.len() && j < right_slice.len() {
if left_slice[i] <= right_slice[j] {
arr[k] = left_slice[i];
i += 1;
} else {
arr[k] = right_slice[j];
j += 1;
}
k += 1;
}
// Copy any remaining elements from the left subarray
while i < left_slice.len() {
arr[k] = left_slice[i];
k += 1;
i += 1;
}
// Copy any remaining elements from the right subarray
while j < right_slice.len() {
arr[k] = right_slice[j];
k += 1;
j += 1;
}
}
/// Sorts a slice using Tim sort algorithm.
///
/// This function sorts the provided slice in-place using the Tim sort algorithm.
///
/// # Arguments
///
/// * `arr` - The slice to be sorted.
pub fn tim_sort<T: Ord + Copy>(arr: &mut [T]) {
let n = arr.len();
let min_run = compute_min_run_length(MIN_MERGE);
// Perform insertion sort on small subarrays
let mut i = 0;
while i < n {
insertion_sort(&mut arr[i..cmp::min(i + MIN_MERGE, n)]);
i += min_run;
}
// Merge sorted subarrays
let mut size = min_run;
while size < n {
let mut left = 0;
while left < n {
let mid = left + size - 1;
let right = cmp::min(left + 2 * size - 1, n - 1);
if mid < right {
merge(arr, left, mid, right);
}
left += 2 * size;
}
size *= 2;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::{have_same_elements, is_sorted};
#[test]
fn min_run_length_returns_correct_value() {
assert_eq!(compute_min_run_length(0), 0);
assert_eq!(compute_min_run_length(10), 10);
assert_eq!(compute_min_run_length(33), 17);
assert_eq!(compute_min_run_length(64), 16);
}
macro_rules! test_merge {
($($name:ident: $inputs:expr,)*) => {
$(
#[test]
fn $name() {
let (input_arr, l, m, r, expected) = $inputs;
let mut arr = input_arr.clone();
merge(&mut arr, l, m, r);
assert_eq!(arr, expected);
}
)*
}
}
test_merge! {
left_and_right_subarrays_into_array: (vec![0, 2, 4, 1, 3, 5], 0, 2, 5, vec![0, 1, 2, 3, 4, 5]),
with_empty_left_subarray: (vec![1, 2, 3], 0, 0, 2, vec![1, 2, 3]),
with_empty_right_subarray: (vec![1, 2, 3], 0, 2, 2, vec![1, 2, 3]),
with_empty_left_and_right_subarrays: (vec![1, 2, 3], 1, 0, 0, vec![1, 2, 3]),
}
macro_rules! test_tim_sort {
($($name:ident: $input:expr,)*) => {
$(
#[test]
fn $name() {
let mut array = $input;
let cloned = array.clone();
tim_sort(&mut array);
assert!(is_sorted(&array) && have_same_elements(&array, &cloned));
}
)*
}
}
test_tim_sort! {
sorts_basic_array_correctly: vec![-2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12],
sorts_long_array_correctly: vec![-2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12, 5, 3, 9, 22, 1, 1, 2, 3, 9, 6, 5, 4, 5, 6, 7, 8, 9, 1],
handles_empty_array: Vec::<i32>::new(),
handles_single_element_array: vec![3],
handles_pre_sorted_array: vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/pigeonhole_sort.rs | src/sorting/pigeonhole_sort.rs | // From Wikipedia: Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements (n) and the length of the range of possible key values (N) are approximately the same. It requires O(n + N) time.
pub fn pigeonhole_sort(array: &mut [i32]) {
if let (Some(min), Some(max)) = (array.iter().min(), array.iter().max()) {
let holes_range: usize = (max - min + 1) as usize;
let mut holes = vec![0; holes_range];
let mut holes_repeat = vec![0; holes_range];
for i in array.iter() {
let index = *i - min;
holes[index as usize] = *i;
holes_repeat[index as usize] += 1;
}
let mut index = 0;
for i in 0..holes_range {
while holes_repeat[i] > 0 {
array[index] = holes[i];
index += 1;
holes_repeat[i] -= 1;
}
}
}
}
#[cfg(test)]
mod tests {
use super::super::is_sorted;
use super::*;
#[test]
fn test1() {
let mut arr1 = [3, 3, 3, 1, 2, 6, 5, 5, 5, 4, 1, 6, 3];
pigeonhole_sort(&mut arr1);
assert!(is_sorted(&arr1));
let mut arr2 = [6, 5, 4, 3, 2, 1];
pigeonhole_sort(&mut arr2);
assert!(is_sorted(&arr2));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/comb_sort.rs | src/sorting/comb_sort.rs | pub fn comb_sort<T: Ord>(arr: &mut [T]) {
let mut gap = arr.len();
let shrink = 1.3;
let mut sorted = false;
while !sorted {
gap = (gap as f32 / shrink).floor() as usize;
if gap <= 1 {
gap = 1;
sorted = true;
}
for i in 0..arr.len() - gap {
let j = i + gap;
if arr[i] > arr[j] {
arr.swap(i, j);
sorted = false;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn descending() {
//descending
let mut ve1 = vec![6, 5, 4, 3, 2, 1];
let cloned = ve1.clone();
comb_sort(&mut ve1);
assert!(is_sorted(&ve1) && have_same_elements(&ve1, &cloned));
}
#[test]
fn ascending() {
//pre-sorted
let mut ve2 = vec![1, 2, 3, 4, 5, 6];
let cloned = ve2.clone();
comb_sort(&mut ve2);
assert!(is_sorted(&ve2) && have_same_elements(&ve2, &cloned));
}
#[test]
fn duplicates() {
//pre-sorted
let mut ve3 = vec![2, 2, 2, 2, 2, 1];
let cloned = ve3.clone();
comb_sort(&mut ve3);
assert!(is_sorted(&ve3) && have_same_elements(&ve3, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/mod.rs | src/sorting/mod.rs | mod bead_sort;
mod binary_insertion_sort;
mod bingo_sort;
mod bitonic_sort;
mod bogo_sort;
mod bubble_sort;
mod bucket_sort;
mod cocktail_shaker_sort;
mod comb_sort;
mod counting_sort;
mod cycle_sort;
mod dutch_national_flag_sort;
mod exchange_sort;
mod gnome_sort;
mod heap_sort;
mod insertion_sort;
mod intro_sort;
mod merge_sort;
mod odd_even_sort;
mod pancake_sort;
mod patience_sort;
mod pigeonhole_sort;
mod quick_sort;
mod quick_sort_3_ways;
mod radix_sort;
mod selection_sort;
mod shell_sort;
mod sleep_sort;
#[cfg(test)]
mod sort_utils;
mod stooge_sort;
mod tim_sort;
mod tree_sort;
mod wave_sort;
mod wiggle_sort;
pub use self::bead_sort::bead_sort;
pub use self::binary_insertion_sort::binary_insertion_sort;
pub use self::bingo_sort::bingo_sort;
pub use self::bitonic_sort::bitonic_sort;
pub use self::bogo_sort::bogo_sort;
pub use self::bubble_sort::bubble_sort;
pub use self::bucket_sort::bucket_sort;
pub use self::cocktail_shaker_sort::cocktail_shaker_sort;
pub use self::comb_sort::comb_sort;
pub use self::counting_sort::counting_sort;
pub use self::counting_sort::generic_counting_sort;
pub use self::cycle_sort::cycle_sort;
pub use self::dutch_national_flag_sort::dutch_national_flag_sort;
pub use self::exchange_sort::exchange_sort;
pub use self::gnome_sort::gnome_sort;
pub use self::heap_sort::heap_sort;
pub use self::insertion_sort::insertion_sort;
pub use self::intro_sort::intro_sort;
pub use self::merge_sort::bottom_up_merge_sort;
pub use self::merge_sort::top_down_merge_sort;
pub use self::odd_even_sort::odd_even_sort;
pub use self::pancake_sort::pancake_sort;
pub use self::patience_sort::patience_sort;
pub use self::pigeonhole_sort::pigeonhole_sort;
pub use self::quick_sort::{partition, quick_sort};
pub use self::quick_sort_3_ways::quick_sort_3_ways;
pub use self::radix_sort::radix_sort;
pub use self::selection_sort::selection_sort;
pub use self::shell_sort::shell_sort;
pub use self::sleep_sort::sleep_sort;
pub use self::stooge_sort::stooge_sort;
pub use self::tim_sort::tim_sort;
pub use self::tree_sort::tree_sort;
pub use self::wave_sort::wave_sort;
pub use self::wiggle_sort::wiggle_sort;
#[cfg(test)]
use std::cmp;
#[cfg(test)]
pub fn have_same_elements<T>(a: &[T], b: &[T]) -> bool
where
// T: cmp::PartialOrd,
// If HashSet is used
T: cmp::PartialOrd + cmp::Eq + std::hash::Hash,
{
use std::collections::HashSet;
if a.len() == b.len() {
// This is O(n^2) but performs better on smaller data sizes
//b.iter().all(|item| a.contains(item))
// This is O(n), performs well on larger data sizes
let set_a: HashSet<&T> = a.iter().collect();
let set_b: HashSet<&T> = b.iter().collect();
set_a == set_b
} else {
false
}
}
#[cfg(test)]
pub fn is_sorted<T>(arr: &[T]) -> bool
where
T: cmp::PartialOrd,
{
arr.windows(2).all(|w| w[0] <= w[1])
}
#[cfg(test)]
pub fn is_descending_sorted<T>(arr: &[T]) -> bool
where
T: cmp::PartialOrd,
{
arr.windows(2).all(|w| w[0] >= w[1])
}
#[cfg(test)]
mod tests {
#[test]
fn is_sorted() {
use super::*;
assert!(is_sorted(&[] as &[isize]));
assert!(is_sorted(&["a"]));
assert!(is_sorted(&[1, 2, 3]));
assert!(is_sorted(&[0, 1, 1]));
assert!(!is_sorted(&[1, 0]));
assert!(!is_sorted(&[2, 3, 1, -1, 5]));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/patience_sort.rs | src/sorting/patience_sort.rs | use std::vec;
pub fn patience_sort<T: Ord + Copy>(arr: &mut [T]) {
if arr.is_empty() {
return;
}
// collect piles from arr
let mut piles: Vec<Vec<T>> = Vec::new();
for &card in arr.iter() {
let mut left = 0usize;
let mut right = piles.len();
while left < right {
let mid = left + (right - left) / 2;
if piles[mid][piles[mid].len() - 1] >= card {
right = mid;
} else {
left = mid + 1;
}
}
if left == piles.len() {
piles.push(vec![card]);
} else {
piles[left].push(card);
}
}
// merge the piles
let mut idx = 0usize;
while let Some((min_id, pile)) = piles
.iter()
.enumerate()
.min_by_key(|(_, pile)| *pile.last().unwrap())
{
arr[idx] = *pile.last().unwrap();
idx += 1;
piles[min_id].pop();
if piles[min_id].is_empty() {
_ = piles.remove(min_id);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn basic() {
let mut array = vec![
-2, 7, 15, -14, 0, 15, 0, 10_033, 7, -7, -4, -13, 5, 8, -14, 12,
];
let cloned = array.clone();
patience_sort(&mut array);
assert!(is_sorted(&array) && have_same_elements(&array, &cloned));
}
#[test]
fn empty() {
let mut array = Vec::<i32>::new();
let cloned = array.clone();
patience_sort(&mut array);
assert!(is_sorted(&array) && have_same_elements(&array, &cloned));
}
#[test]
fn one_element() {
let mut array = vec![3];
let cloned = array.clone();
patience_sort(&mut array);
assert!(is_sorted(&array) && have_same_elements(&array, &cloned));
}
#[test]
fn pre_sorted() {
let mut array = vec![-123_456, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let cloned = array.clone();
patience_sort(&mut array);
assert!(is_sorted(&array) && have_same_elements(&array, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/pancake_sort.rs | src/sorting/pancake_sort.rs | use std::cmp;
pub fn pancake_sort<T>(arr: &mut [T]) -> Vec<T>
where
T: cmp::PartialEq + cmp::Ord + cmp::PartialOrd + Clone,
{
let len = arr.len();
if len < 2 {
arr.to_vec();
}
for i in (0..len).rev() {
let max_index = arr
.iter()
.take(i + 1)
.enumerate()
.max_by_key(|&(_, elem)| elem)
.map(|(idx, _)| idx)
.unwrap();
if max_index != i {
arr[0..=max_index].reverse();
arr[0..=i].reverse();
}
}
arr.to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic() {
let res = pancake_sort(&mut [6, 5, -8, 3, 2, 3]);
assert_eq!(res, vec![-8, 2, 3, 3, 5, 6]);
}
#[test]
fn already_sorted() {
let res = pancake_sort(&mut ["a", "b", "c"]);
assert_eq!(res, vec!["a", "b", "c"]);
}
#[test]
fn odd_number_of_elements() {
let res = pancake_sort(&mut ["d", "a", "c", "e", "b"]);
assert_eq!(res, vec!["a", "b", "c", "d", "e"]);
}
#[test]
fn one_element() {
let res = pancake_sort(&mut [3]);
assert_eq!(res, vec![3]);
}
#[test]
fn empty() {
let res = pancake_sort(&mut [] as &mut [u8]);
assert_eq!(res, vec![]);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/cycle_sort.rs | src/sorting/cycle_sort.rs | // sorts with the minimum number of rewrites. Runs through all values in the array, placing them in their correct spots. O(n^2).
pub fn cycle_sort(arr: &mut [i32]) {
for cycle_start in 0..arr.len() {
let mut item = arr[cycle_start];
let mut pos = cycle_start;
for i in arr.iter().skip(cycle_start + 1) {
if *i < item {
pos += 1;
}
}
if pos == cycle_start {
continue;
}
while item == arr[pos] {
pos += 1;
}
std::mem::swap(&mut arr[pos], &mut item);
while pos != cycle_start {
pos = cycle_start;
for i in arr.iter().skip(cycle_start + 1) {
if *i < item {
pos += 1;
}
}
while item == arr[pos] {
pos += 1;
}
std::mem::swap(&mut arr[pos], &mut item);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn it_works() {
let mut arr1 = [6, 5, 4, 3, 2, 1];
let cloned = arr1;
cycle_sort(&mut arr1);
assert!(is_sorted(&arr1) && have_same_elements(&arr1, &cloned));
arr1 = [12, 343, 21, 90, 3, 21];
let cloned = arr1;
cycle_sort(&mut arr1);
assert!(is_sorted(&arr1) && have_same_elements(&arr1, &cloned));
let mut arr2 = [1];
let cloned = arr2;
cycle_sort(&mut arr2);
assert!(is_sorted(&arr2) && have_same_elements(&arr2, &cloned));
let mut arr3 = [213, 542, 90, -23412, -32, 324, -34, 3324, 54];
let cloned = arr3;
cycle_sort(&mut arr3);
assert!(is_sorted(&arr3) && have_same_elements(&arr3, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/binary_insertion_sort.rs | src/sorting/binary_insertion_sort.rs | fn _binary_search<T: Ord>(arr: &[T], target: &T) -> usize {
let mut low = 0;
let mut high = arr.len();
while low < high {
let mid = low + (high - low) / 2;
if arr[mid] < *target {
low = mid + 1;
} else {
high = mid;
}
}
low
}
pub fn binary_insertion_sort<T: Ord + Clone>(arr: &mut [T]) {
let len = arr.len();
for i in 1..len {
let key = arr[i].clone();
let index = _binary_search(&arr[..i], &key);
arr[index..=i].rotate_right(1);
arr[index] = key;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_binary_insertion_sort() {
let mut arr1 = vec![64, 25, 12, 22, 11];
let mut arr2 = vec![5, 4, 3, 2, 1];
let mut arr3 = vec![1, 2, 3, 4, 5];
let mut arr4: Vec<i32> = vec![]; // Explicitly specify the type for arr4
binary_insertion_sort(&mut arr1);
binary_insertion_sort(&mut arr2);
binary_insertion_sort(&mut arr3);
binary_insertion_sort(&mut arr4);
assert_eq!(arr1, vec![11, 12, 22, 25, 64]);
assert_eq!(arr2, vec![1, 2, 3, 4, 5]);
assert_eq!(arr3, vec![1, 2, 3, 4, 5]);
assert_eq!(arr4, Vec::<i32>::new());
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/sort_utils.rs | src/sorting/sort_utils.rs | use rand::Rng;
use std::time::Instant;
#[cfg(test)]
pub fn generate_random_vec(n: u32, range_l: i32, range_r: i32) -> Vec<i32> {
let mut arr = Vec::<i32>::with_capacity(n as usize);
let mut rng = rand::rng();
let mut count = n;
while count > 0 {
arr.push(rng.random_range(range_l..=range_r));
count -= 1;
}
arr
}
#[cfg(test)]
pub fn generate_nearly_ordered_vec(n: u32, swap_times: u32) -> Vec<i32> {
let mut arr: Vec<i32> = (0..n as i32).collect();
let mut rng = rand::rng();
let mut count = swap_times;
while count > 0 {
arr.swap(
rng.random_range(0..n as usize),
rng.random_range(0..n as usize),
);
count -= 1;
}
arr
}
#[cfg(test)]
pub fn generate_ordered_vec(n: u32) -> Vec<i32> {
generate_nearly_ordered_vec(n, 0)
}
#[cfg(test)]
pub fn generate_reverse_ordered_vec(n: u32) -> Vec<i32> {
let mut arr = generate_ordered_vec(n);
arr.reverse();
arr
}
#[cfg(test)]
pub fn generate_repeated_elements_vec(n: u32, unique_elements: u8) -> Vec<i32> {
let mut rng = rand::rng();
let v = rng.random_range(0..n as i32);
generate_random_vec(n, v, v + unique_elements as i32)
}
#[cfg(test)]
pub fn log_timed<F>(test_name: &str, f: F)
where
F: FnOnce(),
{
let before = Instant::now();
f();
println!("Elapsed time of {:?} is {:?}", test_name, before.elapsed());
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/merge_sort.rs | src/sorting/merge_sort.rs | fn merge<T: Ord + Copy>(arr: &mut [T], mid: usize) {
// Create temporary vectors to support the merge.
let left_half = arr[..mid].to_vec();
let right_half = arr[mid..].to_vec();
// Indexes to track the positions while merging.
let mut l = 0;
let mut r = 0;
for v in arr {
// Choose either the smaller element, or from whichever vec is not exhausted.
if r == right_half.len() || (l < left_half.len() && left_half[l] < right_half[r]) {
*v = left_half[l];
l += 1;
} else {
*v = right_half[r];
r += 1;
}
}
}
pub fn top_down_merge_sort<T: Ord + Copy>(arr: &mut [T]) {
if arr.len() > 1 {
let mid = arr.len() / 2;
// Sort the left half recursively.
top_down_merge_sort(&mut arr[..mid]);
// Sort the right half recursively.
top_down_merge_sort(&mut arr[mid..]);
// Combine the two halves.
merge(arr, mid);
}
}
pub fn bottom_up_merge_sort<T: Copy + Ord>(a: &mut [T]) {
if a.len() > 1 {
let len: usize = a.len();
let mut sub_array_size: usize = 1;
while sub_array_size < len {
let mut start_index: usize = 0;
// still have more than one sub-arrays to merge
while len - start_index > sub_array_size {
let end_idx: usize = if start_index + 2 * sub_array_size > len {
len
} else {
start_index + 2 * sub_array_size
};
// merge a[start_index..start_index+sub_array_size] and a[start_index+sub_array_size..end_idx]
// NOTE: mid is a relative index number starting from `start_index`
merge(&mut a[start_index..end_idx], sub_array_size);
// update `start_index` to merge the next sub-arrays
start_index = end_idx;
}
sub_array_size *= 2;
}
}
}
#[cfg(test)]
mod tests {
#[cfg(test)]
mod top_down_merge_sort {
use super::super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn basic() {
let mut res = vec![10, 8, 4, 3, 1, 9, 2, 7, 5, 6];
let cloned = res.clone();
top_down_merge_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn basic_string() {
let mut res = vec!["a", "bb", "d", "cc"];
let cloned = res.clone();
top_down_merge_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn empty() {
let mut res = Vec::<u8>::new();
let cloned = res.clone();
top_down_merge_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn one_element() {
let mut res = vec![1];
let cloned = res.clone();
top_down_merge_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn pre_sorted() {
let mut res = vec![1, 2, 3, 4];
let cloned = res.clone();
top_down_merge_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn reverse_sorted() {
let mut res = vec![4, 3, 2, 1];
let cloned = res.clone();
top_down_merge_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
}
#[cfg(test)]
mod bottom_up_merge_sort {
use super::super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn basic() {
let mut res = vec![10, 8, 4, 3, 1, 9, 2, 7, 5, 6];
let cloned = res.clone();
bottom_up_merge_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn basic_string() {
let mut res = vec!["a", "bb", "d", "cc"];
let cloned = res.clone();
bottom_up_merge_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn empty() {
let mut res = Vec::<u8>::new();
let cloned = res.clone();
bottom_up_merge_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn one_element() {
let mut res = vec![1];
let cloned = res.clone();
bottom_up_merge_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn pre_sorted() {
let mut res = vec![1, 2, 3, 4];
let cloned = res.clone();
bottom_up_merge_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn reverse_sorted() {
let mut res = vec![4, 3, 2, 1];
let cloned = res.clone();
bottom_up_merge_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/bingo_sort.rs | src/sorting/bingo_sort.rs | use std::cmp::{max, min};
// Function for finding the maximum and minimum element of the Array
fn max_min(vec: &[i32], bingo: &mut i32, next_bingo: &mut i32) {
for &element in vec.iter().skip(1) {
*bingo = min(*bingo, element);
*next_bingo = max(*next_bingo, element);
}
}
pub fn bingo_sort(vec: &mut [i32]) {
if vec.is_empty() {
return;
}
let mut bingo = vec[0];
let mut next_bingo = vec[0];
max_min(vec, &mut bingo, &mut next_bingo);
let largest_element = next_bingo;
let mut next_element_pos = 0;
for (bingo, _next_bingo) in (bingo..=largest_element).zip(bingo..=largest_element) {
let start_pos = next_element_pos;
for i in start_pos..vec.len() {
if vec[i] == bingo {
vec.swap(i, next_element_pos);
next_element_pos += 1;
}
}
}
}
#[allow(dead_code)]
fn print_array(arr: &[i32]) {
print!("Sorted Array: ");
for &element in arr {
print!("{element} ");
}
println!();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bingo_sort() {
let mut arr = vec![5, 4, 8, 5, 4, 8, 5, 4, 4, 4];
bingo_sort(&mut arr);
assert_eq!(arr, vec![4, 4, 4, 4, 4, 5, 5, 5, 8, 8]);
let mut arr2 = vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
bingo_sort(&mut arr2);
assert_eq!(arr2, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let mut arr3 = vec![0, 1, 0, 1, 0, 1];
bingo_sort(&mut arr3);
assert_eq!(arr3, vec![0, 0, 0, 1, 1, 1]);
}
#[test]
fn test_empty_array() {
let mut arr = Vec::new();
bingo_sort(&mut arr);
assert_eq!(arr, Vec::new());
}
#[test]
fn test_single_element_array() {
let mut arr = vec![42];
bingo_sort(&mut arr);
assert_eq!(arr, vec![42]);
}
#[test]
fn test_negative_numbers() {
let mut arr = vec![-5, -4, -3, -2, -1];
bingo_sort(&mut arr);
assert_eq!(arr, vec![-5, -4, -3, -2, -1]);
}
#[test]
fn test_already_sorted() {
let mut arr = vec![1, 2, 3, 4, 5];
bingo_sort(&mut arr);
assert_eq!(arr, vec![1, 2, 3, 4, 5]);
}
#[test]
fn test_reverse_sorted() {
let mut arr = vec![5, 4, 3, 2, 1];
bingo_sort(&mut arr);
assert_eq!(arr, vec![1, 2, 3, 4, 5]);
}
#[test]
fn test_duplicates() {
let mut arr = vec![1, 2, 3, 4, 5, 1, 2, 3, 4, 5];
bingo_sort(&mut arr);
assert_eq!(arr, vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5]);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/odd_even_sort.rs | src/sorting/odd_even_sort.rs | pub fn odd_even_sort<T: Ord>(arr: &mut [T]) {
let len = arr.len();
if len == 0 {
return;
}
let mut sorted = false;
while !sorted {
sorted = true;
for i in (1..len - 1).step_by(2) {
if arr[i] > arr[i + 1] {
arr.swap(i, i + 1);
sorted = false;
}
}
for i in (0..len - 1).step_by(2) {
if arr[i] > arr[i + 1] {
arr.swap(i, i + 1);
sorted = false;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn basic() {
let mut arr = vec![3, 5, 1, 2, 4, 6];
let cloned = arr.clone();
odd_even_sort(&mut arr);
assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned));
}
#[test]
fn empty() {
let mut arr = Vec::<i32>::new();
let cloned = arr.clone();
odd_even_sort(&mut arr);
assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned));
}
#[test]
fn one_element() {
let mut arr = vec![3];
let cloned = arr.clone();
odd_even_sort(&mut arr);
assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned));
}
#[test]
fn pre_sorted() {
let mut arr = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let cloned = arr.clone();
odd_even_sort(&mut arr);
assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/insertion_sort.rs | src/sorting/insertion_sort.rs | /// Sorts a mutable slice using in-place insertion sort algorithm.
///
/// Time complexity is `O(n^2)`, where `n` is the number of elements.
/// Space complexity is `O(1)` as it sorts elements in-place.
pub fn insertion_sort<T: Ord + Copy>(arr: &mut [T]) {
for i in 1..arr.len() {
let mut j = i;
let cur = arr[i];
while j > 0 && cur < arr[j - 1] {
arr[j] = arr[j - 1];
j -= 1;
}
arr[j] = cur;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn empty() {
let mut arr: [u8; 0] = [];
let cloned = arr;
insertion_sort(&mut arr);
assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned));
}
#[test]
fn one_element() {
let mut arr: [char; 1] = ['a'];
let cloned = arr;
insertion_sort(&mut arr);
assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned));
}
#[test]
fn already_sorted() {
let mut arr: [&str; 3] = ["a", "b", "c"];
let cloned = arr;
insertion_sort(&mut arr);
assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned));
}
#[test]
fn basic() {
let mut arr: [&str; 4] = ["d", "a", "c", "b"];
let cloned = arr;
insertion_sort(&mut arr);
assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned));
}
#[test]
fn odd_number_of_elements() {
let mut arr: Vec<&str> = vec!["d", "a", "c", "e", "b"];
let cloned = arr.clone();
insertion_sort(&mut arr);
assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned));
}
#[test]
fn repeated_elements() {
let mut arr: Vec<usize> = vec![542, 542, 542, 542];
let cloned = arr.clone();
insertion_sort(&mut arr);
assert!(is_sorted(&arr) && have_same_elements(&arr, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/exchange_sort.rs | src/sorting/exchange_sort.rs | // sorts through swapping the first value until it is at the right position, and repeating for all the following.
pub fn exchange_sort(arr: &mut [i32]) {
let length = arr.len();
for number1 in 0..length {
for number2 in (number1 + 1)..length {
if arr[number2] < arr[number1] {
arr.swap(number1, number2)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn it_works() {
let mut arr1 = [6, 5, 4, 3, 2, 1];
let cloned = arr1;
exchange_sort(&mut arr1);
assert!(is_sorted(&arr1) && have_same_elements(&arr1, &cloned));
arr1 = [12, 343, 21, 90, 3, 21];
let cloned = arr1;
exchange_sort(&mut arr1);
assert!(is_sorted(&arr1) && have_same_elements(&arr1, &cloned));
let mut arr2 = [1];
let cloned = arr2;
exchange_sort(&mut arr2);
assert!(is_sorted(&arr2) && have_same_elements(&arr2, &cloned));
let mut arr3 = [213, 542, 90, -23412, -32, 324, -34, 3324, 54];
let cloned = arr3;
exchange_sort(&mut arr3);
assert!(is_sorted(&arr3) && have_same_elements(&arr3, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/quick_sort.rs | src/sorting/quick_sort.rs | pub fn partition<T: PartialOrd>(arr: &mut [T], lo: usize, hi: usize) -> usize {
let pivot = hi;
let mut i = lo;
let mut j = hi - 1;
loop {
while arr[i] < arr[pivot] {
i += 1;
}
while j > 0 && arr[j] > arr[pivot] {
j -= 1;
}
if j == 0 || i >= j {
break;
} else if arr[i] == arr[j] {
i += 1;
j -= 1;
} else {
arr.swap(i, j);
}
}
arr.swap(i, pivot);
i
}
fn _quick_sort<T: Ord>(arr: &mut [T], mut lo: usize, mut hi: usize) {
while lo < hi {
let pivot = partition(arr, lo, hi);
if pivot - lo < hi - pivot {
if pivot > 0 {
_quick_sort(arr, lo, pivot - 1);
}
lo = pivot + 1;
} else {
_quick_sort(arr, pivot + 1, hi);
hi = pivot - 1;
}
}
}
pub fn quick_sort<T: Ord>(arr: &mut [T]) {
let len = arr.len();
if len > 1 {
_quick_sort(arr, 0, len - 1);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
use crate::sorting::sort_utils;
#[test]
fn basic() {
let mut res = vec![10, 8, 4, 3, 1, 9, 2, 7, 5, 6];
let cloned = res.clone();
quick_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn basic_string() {
let mut res = vec!["a", "bb", "d", "cc"];
let cloned = res.clone();
quick_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn empty() {
let mut res = Vec::<u8>::new();
let cloned = res.clone();
quick_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn one_element() {
let mut res = vec![1];
let cloned = res.clone();
quick_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn pre_sorted() {
let mut res = vec![1, 2, 3, 4];
let cloned = res.clone();
quick_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn reverse_sorted() {
let mut res = vec![4, 3, 2, 1];
let cloned = res.clone();
quick_sort(&mut res);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn large_elements() {
let mut res = sort_utils::generate_random_vec(300000, 0, 1000000);
let cloned = res.clone();
sort_utils::log_timed("large elements test", || {
quick_sort(&mut res);
});
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn nearly_ordered_elements() {
let mut res = sort_utils::generate_nearly_ordered_vec(3000, 10);
let cloned = res.clone();
sort_utils::log_timed("nearly ordered elements test", || {
quick_sort(&mut res);
});
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn repeated_elements() {
let mut res = sort_utils::generate_repeated_elements_vec(1000000, 3);
let cloned = res.clone();
sort_utils::log_timed("repeated elements test", || {
quick_sort(&mut res);
});
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/bucket_sort.rs | src/sorting/bucket_sort.rs | /// Sort a slice using bucket sort algorithm.
///
/// Time complexity is `O(n + k)` on average, where `n` is the number of elements,
/// `k` is the number of buckets used in process.
///
/// Space complexity is `O(n + k)`, as it sorts not in-place.
pub fn bucket_sort(arr: &[usize]) -> Vec<usize> {
if arr.is_empty() {
return vec![];
}
let max = *arr.iter().max().unwrap();
let len = arr.len();
let mut buckets = vec![vec![]; len + 1];
for x in arr {
buckets[len * *x / max].push(*x);
}
for bucket in buckets.iter_mut() {
super::insertion_sort(bucket);
}
let mut result = vec![];
for bucket in buckets {
for x in bucket {
result.push(x);
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn empty() {
let arr: [usize; 0] = [];
let cloned = arr;
let res = bucket_sort(&arr);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn one_element() {
let arr: [usize; 1] = [4];
let cloned = arr;
let res = bucket_sort(&arr);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn already_sorted() {
let arr: [usize; 3] = [10, 19, 105];
let cloned = arr;
let res = bucket_sort(&arr);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn basic() {
let arr: [usize; 4] = [35, 53, 1, 0];
let cloned = arr;
let res = bucket_sort(&arr);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn odd_number_of_elements() {
let arr: [usize; 5] = [1, 21, 5, 11, 58];
let cloned = arr;
let res = bucket_sort(&arr);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
#[test]
fn repeated_elements() {
let arr: [usize; 4] = [542, 542, 542, 542];
let cloned = arr;
let res = bucket_sort(&arr);
assert!(is_sorted(&res) && have_same_elements(&res, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/shell_sort.rs | src/sorting/shell_sort.rs | pub fn shell_sort<T: Ord + Copy>(values: &mut [T]) {
// shell sort works by swiping the value at a given gap and decreasing the gap to 1
fn insertion<T: Ord + Copy>(values: &mut [T], start: usize, gap: usize) {
for i in ((start + gap)..values.len()).step_by(gap) {
let val_current = values[i];
let mut pos = i;
// make swaps
while pos >= gap && values[pos - gap] > val_current {
values[pos] = values[pos - gap];
pos -= gap;
}
values[pos] = val_current;
}
}
let mut count_sublist = values.len() / 2; // makes gap as long as half of the array
while count_sublist > 0 {
for pos_start in 0..count_sublist {
insertion(values, pos_start, count_sublist);
}
count_sublist /= 2; // makes gap as half of previous
}
}
#[cfg(test)]
mod test {
use super::shell_sort;
use crate::sorting::have_same_elements;
use crate::sorting::is_sorted;
#[test]
fn basic() {
let mut vec = vec![3, 5, 6, 3, 1, 4];
let cloned = vec.clone();
shell_sort(&mut vec);
assert!(is_sorted(&vec) && have_same_elements(&vec, &cloned));
}
#[test]
fn empty() {
let mut vec: Vec<i32> = vec![];
let cloned = vec.clone();
shell_sort(&mut vec);
assert!(is_sorted(&vec) && have_same_elements(&vec, &cloned));
}
#[test]
fn reverse() {
let mut vec = vec![6, 5, 4, 3, 2, 1];
let cloned = vec.clone();
shell_sort(&mut vec);
assert!(is_sorted(&vec) && have_same_elements(&vec, &cloned));
}
#[test]
fn already_sorted() {
let mut vec = vec![1, 2, 3, 4, 5, 6];
let cloned = vec.clone();
shell_sort(&mut vec);
assert!(is_sorted(&vec) && have_same_elements(&vec, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/intro_sort.rs | src/sorting/intro_sort.rs | // Intro Sort (Also known as Introspective Sort)
// Introspective Sort is hybrid sort (Quick Sort + Heap Sort + Insertion Sort)
// https://en.wikipedia.org/wiki/Introsort
fn insertion_sort<T: Ord>(arr: &mut [T]) {
for i in 1..arr.len() {
let mut j = i;
while j > 0 && arr[j] < arr[j - 1] {
arr.swap(j, j - 1);
j -= 1;
}
}
}
fn heapify<T: Ord>(arr: &mut [T], n: usize, i: usize) {
let mut largest = i;
let left = 2 * i + 1;
let right = 2 * i + 2;
if left < n && arr[left] > arr[largest] {
largest = left;
}
if right < n && arr[right] > arr[largest] {
largest = right;
}
if largest != i {
arr.swap(i, largest);
heapify(arr, n, largest);
}
}
fn heap_sort<T: Ord>(arr: &mut [T]) {
let n = arr.len();
// Build a max-heap
for i in (0..n / 2).rev() {
heapify(arr, n, i);
}
// Extract elements from the heap one by one
for i in (0..n).rev() {
arr.swap(0, i);
heapify(arr, i, 0);
}
}
pub fn intro_sort<T: Ord>(arr: &mut [T]) {
let len = arr.len();
let max_depth = (2.0 * len as f64).log2() as usize + 1;
fn intro_sort_recursive<T: Ord>(arr: &mut [T], max_depth: usize) {
let len = arr.len();
if len <= 16 {
insertion_sort(arr);
} else if max_depth == 0 {
heap_sort(arr);
} else {
let pivot = partition(arr);
intro_sort_recursive(&mut arr[..pivot], max_depth - 1);
intro_sort_recursive(&mut arr[pivot + 1..], max_depth - 1);
}
}
fn partition<T: Ord>(arr: &mut [T]) -> usize {
let len = arr.len();
let pivot_index = len / 2;
arr.swap(pivot_index, len - 1);
let mut i = 0;
for j in 0..len - 1 {
if arr[j] <= arr[len - 1] {
arr.swap(i, j);
i += 1;
}
}
arr.swap(i, len - 1);
i
}
intro_sort_recursive(arr, max_depth);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_intro_sort() {
// Test with integers
let mut arr1 = vec![67, 34, 29, 15, 21, 9, 99];
intro_sort(&mut arr1);
assert_eq!(arr1, vec![9, 15, 21, 29, 34, 67, 99]);
// Test with strings
let mut arr2 = vec!["sydney", "london", "tokyo", "beijing", "mumbai"];
intro_sort(&mut arr2);
assert_eq!(arr2, vec!["beijing", "london", "mumbai", "sydney", "tokyo"]);
// Test with an empty array
let mut arr3: Vec<i32> = vec![];
intro_sort(&mut arr3);
assert_eq!(arr3, vec![]);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/bitonic_sort.rs | src/sorting/bitonic_sort.rs | fn _comp_and_swap<T: Ord>(array: &mut [T], left: usize, right: usize, ascending: bool) {
if (ascending && array[left] > array[right]) || (!ascending && array[left] < array[right]) {
array.swap(left, right);
}
}
fn _bitonic_merge<T: Ord>(array: &mut [T], low: usize, length: usize, ascending: bool) {
if length > 1 {
let middle = length / 2;
for i in low..(low + middle) {
_comp_and_swap(array, i, i + middle, ascending);
}
_bitonic_merge(array, low, middle, ascending);
_bitonic_merge(array, low + middle, middle, ascending);
}
}
pub fn bitonic_sort<T: Ord>(array: &mut [T], low: usize, length: usize, ascending: bool) {
if length > 1 {
let middle = length / 2;
bitonic_sort(array, low, middle, true);
bitonic_sort(array, low + middle, middle, false);
_bitonic_merge(array, low, length, ascending);
}
}
//Note that this program works only when size of input is a power of 2.
#[cfg(test)]
mod tests {
use super::*;
use crate::sorting::have_same_elements;
use crate::sorting::is_descending_sorted;
use crate::sorting::is_sorted;
#[test]
fn descending() {
//descending
let mut ve1 = vec![6, 5, 4, 3];
let cloned = ve1.clone();
bitonic_sort(&mut ve1, 0, 4, true);
assert!(is_sorted(&ve1) && have_same_elements(&ve1, &cloned));
}
#[test]
fn ascending() {
//pre-sorted
let mut ve2 = vec![1, 2, 3, 4];
let cloned = ve2.clone();
bitonic_sort(&mut ve2, 0, 4, false);
assert!(is_descending_sorted(&ve2) && have_same_elements(&ve2, &cloned));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/palindrome_partitioning.rs | src/dynamic_programming/palindrome_partitioning.rs | /// Finds the minimum cuts needed for a palindrome partitioning of a string
///
/// Given a string s, partition s such that every substring of the partition is a palindrome.
/// This function returns the minimum number of cuts needed.
///
/// Time Complexity: O(n^2)
/// Space Complexity: O(n^2)
///
/// # Arguments
///
/// * `s` - The input string to partition
///
/// # Returns
///
/// The minimum number of cuts needed
///
/// # Examples
///
/// ```
/// use the_algorithms_rust::dynamic_programming::minimum_palindrome_partitions;
///
/// assert_eq!(minimum_palindrome_partitions("aab"), 1);
/// assert_eq!(minimum_palindrome_partitions("aaa"), 0);
/// assert_eq!(minimum_palindrome_partitions("ababbbabbababa"), 3);
/// ```
///
/// # Algorithm Explanation
///
/// The algorithm uses dynamic programming with two key data structures:
/// - `cut[i]`: minimum cuts needed for substring from index 0 to i
/// - `is_palindromic[j][i]`: whether substring from index j to i is a palindrome
///
/// For each position i, we check all possible starting positions j to determine
/// if the substring s[j..=i] is a palindrome. If it is, we update the minimum
/// cut count accordingly.
///
/// Reference: <https://www.youtube.com/watch?v=_H8V5hJUGd0>
pub fn minimum_palindrome_partitions(s: &str) -> usize {
let chars: Vec<char> = s.chars().collect();
let length = chars.len();
if length == 0 {
return 0;
}
// cut[i] represents the minimum cuts needed for substring from 0 to i
let mut cut = vec![0; length];
// is_palindromic[j][i] represents whether substring from j to i is a palindrome
let mut is_palindromic = vec![vec![false; length]; length];
for i in 0..length {
let mut mincut = i;
for j in 0..=i {
// Check if substring from j to i is a palindrome
// A substring is a palindrome if:
// 1. The characters at both ends match (chars[i] == chars[j])
// 2. AND either:
// - The substring length is less than 2 (single char or two same chars)
// - OR the inner substring (j+1 to i-1) is also a palindrome
if chars[i] == chars[j] && (i - j < 2 || is_palindromic[j + 1][i - 1]) {
is_palindromic[j][i] = true;
mincut = if j == 0 {
// If the entire substring from 0 to i is a palindrome, no cuts needed
0
} else {
// Otherwise, take minimum of current mincut and (cuts up to j-1) + 1
mincut.min(cut[j - 1] + 1)
};
}
}
cut[i] = mincut;
}
cut[length - 1]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic_cases() {
// "aab" -> "aa" | "b" = 1 cut
assert_eq!(minimum_palindrome_partitions("aab"), 1);
// "aaa" is already a palindrome = 0 cuts
assert_eq!(minimum_palindrome_partitions("aaa"), 0);
// Complex case
assert_eq!(minimum_palindrome_partitions("ababbbabbababa"), 3);
}
#[test]
fn test_edge_cases() {
// Empty string
assert_eq!(minimum_palindrome_partitions(""), 0);
// Single character is always a palindrome
assert_eq!(minimum_palindrome_partitions("a"), 0);
// Two different characters need 1 cut
assert_eq!(minimum_palindrome_partitions("ab"), 1);
}
#[test]
fn test_palindromes() {
// Already a palindrome
assert_eq!(minimum_palindrome_partitions("racecar"), 0);
assert_eq!(minimum_palindrome_partitions("noon"), 0);
assert_eq!(minimum_palindrome_partitions("abba"), 0);
}
#[test]
fn test_non_palindromes() {
// All different characters need n-1 cuts
assert_eq!(minimum_palindrome_partitions("abcde"), 4);
// Two pairs need 1 cut
assert_eq!(minimum_palindrome_partitions("aabb"), 1);
}
#[test]
fn test_longer_strings() {
assert_eq!(minimum_palindrome_partitions("aaabaa"), 1);
assert_eq!(minimum_palindrome_partitions("abcbm"), 2);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/matrix_chain_multiply.rs | src/dynamic_programming/matrix_chain_multiply.rs | //! This module implements a dynamic programming solution to find the minimum
//! number of multiplications needed to multiply a chain of matrices with given dimensions.
//!
//! The algorithm uses a dynamic programming approach with tabulation to calculate the minimum
//! number of multiplications required for matrix chain multiplication.
//!
//! # Time Complexity
//!
//! The algorithm runs in O(n^3) time complexity and O(n^2) space complexity, where n is the
//! number of matrices.
/// Custom error types for matrix chain multiplication
#[derive(Debug, PartialEq)]
pub enum MatrixChainMultiplicationError {
EmptyDimensions,
InsufficientDimensions,
}
/// Calculates the minimum number of scalar multiplications required to multiply a chain
/// of matrices with given dimensions.
///
/// # Arguments
///
/// * `dimensions`: A vector where each element represents the dimensions of consecutive matrices
/// in the chain. For example, [1, 2, 3, 4] represents matrices of dimensions (1x2), (2x3), and (3x4).
///
/// # Returns
///
/// The minimum number of scalar multiplications needed to compute the product of the matrices
/// in the optimal order.
///
/// # Errors
///
/// Returns an error if the input is invalid (i.e., empty or length less than 2).
pub fn matrix_chain_multiply(
dimensions: Vec<usize>,
) -> Result<usize, MatrixChainMultiplicationError> {
if dimensions.is_empty() {
return Err(MatrixChainMultiplicationError::EmptyDimensions);
}
if dimensions.len() == 1 {
return Err(MatrixChainMultiplicationError::InsufficientDimensions);
}
let mut min_operations = vec![vec![0; dimensions.len()]; dimensions.len()];
(2..dimensions.len()).for_each(|chain_len| {
(0..dimensions.len() - chain_len).for_each(|start| {
let end = start + chain_len;
min_operations[start][end] = (start + 1..end)
.map(|split| {
min_operations[start][split]
+ min_operations[split][end]
+ dimensions[start] * dimensions[split] * dimensions[end]
})
.min()
.unwrap_or(usize::MAX);
});
});
Ok(min_operations[0][dimensions.len() - 1])
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_cases {
($($name:ident: $test_case:expr,)*) => {
$(
#[test]
fn $name() {
let (input, expected) = $test_case;
assert_eq!(matrix_chain_multiply(input.clone()), expected);
assert_eq!(matrix_chain_multiply(input.into_iter().rev().collect()), expected);
}
)*
};
}
test_cases! {
basic_chain_of_matrices: (vec![1, 2, 3, 4], Ok(18)),
chain_of_large_matrices: (vec![40, 20, 30, 10, 30], Ok(26000)),
long_chain_of_matrices: (vec![1, 2, 3, 4, 3, 5, 7, 6, 10], Ok(182)),
complex_chain_of_matrices: (vec![4, 10, 3, 12, 20, 7], Ok(1344)),
empty_dimensions_input: (vec![], Err(MatrixChainMultiplicationError::EmptyDimensions)),
single_dimensions_input: (vec![10], Err(MatrixChainMultiplicationError::InsufficientDimensions)),
single_matrix_input: (vec![10, 20], Ok(0)),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/minimum_cost_path.rs | src/dynamic_programming/minimum_cost_path.rs | use std::cmp::min;
/// Represents possible errors that can occur when calculating the minimum cost path in a matrix.
#[derive(Debug, PartialEq, Eq)]
pub enum MatrixError {
/// Error indicating that the matrix is empty or has empty rows.
EmptyMatrix,
/// Error indicating that the matrix is not rectangular in shape.
NonRectangularMatrix,
}
/// Computes the minimum cost path from the top-left to the bottom-right
/// corner of a matrix, where movement is restricted to right and down directions.
///
/// # Arguments
///
/// * `matrix` - A 2D vector of positive integers, where each element represents
/// the cost to step on that cell.
///
/// # Returns
///
/// * `Ok(usize)` - The minimum path cost to reach the bottom-right corner from
/// the top-left corner of the matrix.
/// * `Err(MatrixError)` - An error if the matrix is empty or improperly formatted.
///
/// # Complexity
///
/// * Time complexity: `O(m * n)`, where `m` is the number of rows
/// and `n` is the number of columns in the input matrix.
/// * Space complexity: `O(n)`, as only a single row of cumulative costs
/// is stored at any time.
pub fn minimum_cost_path(matrix: Vec<Vec<usize>>) -> Result<usize, MatrixError> {
// Check if the matrix is rectangular
if !matrix.iter().all(|row| row.len() == matrix[0].len()) {
return Err(MatrixError::NonRectangularMatrix);
}
// Check if the matrix is empty or contains empty rows
if matrix.is_empty() || matrix.iter().all(|row| row.is_empty()) {
return Err(MatrixError::EmptyMatrix);
}
// Initialize the first row of the cost vector
let mut cost = matrix[0]
.iter()
.scan(0, |acc, &val| {
*acc += val;
Some(*acc)
})
.collect::<Vec<_>>();
// Process each row from the second to the last
for row in matrix.iter().skip(1) {
// Update the first element of cost for this row
cost[0] += row[0];
// Update the rest of the elements in the current row of cost
for col in 1..matrix[0].len() {
cost[col] = row[col] + min(cost[col - 1], cost[col]);
}
}
// The last element in cost contains the minimum path cost to the bottom-right corner
Ok(cost[matrix[0].len() - 1])
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! minimum_cost_path_tests {
($($name:ident: $test_case:expr,)*) => {
$(
#[test]
fn $name() {
let (matrix, expected) = $test_case;
assert_eq!(minimum_cost_path(matrix), expected);
}
)*
};
}
minimum_cost_path_tests! {
basic: (
vec![
vec![2, 1, 4],
vec![2, 1, 3],
vec![3, 2, 1]
],
Ok(7)
),
single_element: (
vec![
vec![5]
],
Ok(5)
),
single_row: (
vec![
vec![1, 3, 2, 1, 5]
],
Ok(12)
),
single_column: (
vec![
vec![1],
vec![3],
vec![2],
vec![1],
vec![5]
],
Ok(12)
),
large_matrix: (
vec![
vec![1, 3, 1, 5],
vec![2, 1, 4, 2],
vec![3, 2, 1, 3],
vec![4, 3, 2, 1]
],
Ok(10)
),
uniform_matrix: (
vec![
vec![1, 1, 1],
vec![1, 1, 1],
vec![1, 1, 1]
],
Ok(5)
),
increasing_values: (
vec![
vec![1, 2, 3],
vec![4, 5, 6],
vec![7, 8, 9]
],
Ok(21)
),
high_cost_path: (
vec![
vec![1, 100, 1],
vec![1, 100, 1],
vec![1, 1, 1]
],
Ok(5)
),
complex_matrix: (
vec![
vec![5, 9, 6, 8],
vec![1, 4, 7, 3],
vec![2, 1, 8, 2],
vec![3, 6, 9, 4]
],
Ok(23)
),
empty_matrix: (
vec![],
Err(MatrixError::EmptyMatrix)
),
empty_row: (
vec![
vec![],
vec![],
vec![]
],
Err(MatrixError::EmptyMatrix)
),
non_rectangular: (
vec![
vec![1, 2, 3],
vec![4, 5],
vec![6, 7, 8]
],
Err(MatrixError::NonRectangularMatrix)
),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/knapsack.rs | src/dynamic_programming/knapsack.rs | //! This module provides functionality to solve the knapsack problem using dynamic programming.
//! It includes structures for items and solutions, and functions to compute the optimal solution.
use std::cmp::Ordering;
/// Represents an item with a weight and a value.
#[derive(Debug, PartialEq, Eq)]
pub struct Item {
weight: usize,
value: usize,
}
/// Represents the solution to the knapsack problem.
#[derive(Debug, PartialEq, Eq)]
pub struct KnapsackSolution {
/// The optimal profit obtained.
optimal_profit: usize,
/// The total weight of items included in the solution.
total_weight: usize,
/// The indices of items included in the solution. Indices might not be unique.
item_indices: Vec<usize>,
}
/// Solves the knapsack problem and returns the optimal profit, total weight, and indices of items included.
///
/// # Arguments:
/// * `capacity` - The maximum weight capacity of the knapsack.
/// * `items` - A vector of `Item` structs, each representing an item with weight and value.
///
/// # Returns:
/// A `KnapsackSolution` struct containing:
/// - `optimal_profit` - The maximum profit achievable with the given capacity and items.
/// - `total_weight` - The total weight of items included in the solution.
/// - `item_indices` - Indices of items included in the solution. Indices might not be unique.
///
/// # Note:
/// The indices of items in the solution might not be unique.
/// This function assumes that `items` is non-empty.
///
/// # Complexity:
/// - Time complexity: O(num_items * capacity)
/// - Space complexity: O(num_items * capacity)
///
/// where `num_items` is the number of items and `capacity` is the knapsack capacity.
pub fn knapsack(capacity: usize, items: Vec<Item>) -> KnapsackSolution {
let num_items = items.len();
let item_weights: Vec<usize> = items.iter().map(|item| item.weight).collect();
let item_values: Vec<usize> = items.iter().map(|item| item.value).collect();
let knapsack_matrix = generate_knapsack_matrix(capacity, &item_weights, &item_values);
let items_included =
retrieve_knapsack_items(&item_weights, &knapsack_matrix, num_items, capacity);
let total_weight = items_included
.iter()
.map(|&index| item_weights[index - 1])
.sum();
KnapsackSolution {
optimal_profit: knapsack_matrix[num_items][capacity],
total_weight,
item_indices: items_included,
}
}
/// Generates the knapsack matrix (`num_items`, `capacity`) with maximum values.
///
/// # Arguments:
/// * `capacity` - knapsack capacity
/// * `item_weights` - weights of each item
/// * `item_values` - values of each item
fn generate_knapsack_matrix(
capacity: usize,
item_weights: &[usize],
item_values: &[usize],
) -> Vec<Vec<usize>> {
let num_items = item_weights.len();
(0..=num_items).fold(
vec![vec![0; capacity + 1]; num_items + 1],
|mut matrix, item_index| {
(0..=capacity).for_each(|current_capacity| {
matrix[item_index][current_capacity] = if item_index == 0 || current_capacity == 0 {
0
} else if item_weights[item_index - 1] <= current_capacity {
usize::max(
item_values[item_index - 1]
+ matrix[item_index - 1]
[current_capacity - item_weights[item_index - 1]],
matrix[item_index - 1][current_capacity],
)
} else {
matrix[item_index - 1][current_capacity]
};
});
matrix
},
)
}
/// Retrieves the indices of items included in the optimal knapsack solution.
///
/// # Arguments:
/// * `item_weights` - weights of each item
/// * `knapsack_matrix` - knapsack matrix with maximum values
/// * `item_index` - number of items to consider (initially the total number of items)
/// * `remaining_capacity` - remaining capacity of the knapsack
///
/// # Returns
/// A vector of item indices included in the optimal solution. The indices might not be unique.
fn retrieve_knapsack_items(
item_weights: &[usize],
knapsack_matrix: &[Vec<usize>],
item_index: usize,
remaining_capacity: usize,
) -> Vec<usize> {
match item_index {
0 => vec![],
_ => {
let current_value = knapsack_matrix[item_index][remaining_capacity];
let previous_value = knapsack_matrix[item_index - 1][remaining_capacity];
match current_value.cmp(&previous_value) {
Ordering::Greater => {
let mut knap = retrieve_knapsack_items(
item_weights,
knapsack_matrix,
item_index - 1,
remaining_capacity - item_weights[item_index - 1],
);
knap.push(item_index);
knap
}
Ordering::Equal | Ordering::Less => retrieve_knapsack_items(
item_weights,
knapsack_matrix,
item_index - 1,
remaining_capacity,
),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! knapsack_tests {
($($name:ident: $test_case:expr,)*) => {
$(
#[test]
fn $name() {
let (capacity, items, expected) = $test_case;
assert_eq!(expected, knapsack(capacity, items));
}
)*
}
}
knapsack_tests! {
test_basic_knapsack_small: (
165,
vec![
Item { weight: 23, value: 92 },
Item { weight: 31, value: 57 },
Item { weight: 29, value: 49 },
Item { weight: 44, value: 68 },
Item { weight: 53, value: 60 },
Item { weight: 38, value: 43 },
Item { weight: 63, value: 67 },
Item { weight: 85, value: 84 },
Item { weight: 89, value: 87 },
Item { weight: 82, value: 72 }
],
KnapsackSolution {
optimal_profit: 309,
total_weight: 165,
item_indices: vec![1, 2, 3, 4, 6]
}
),
test_basic_knapsack_tiny: (
26,
vec![
Item { weight: 12, value: 24 },
Item { weight: 7, value: 13 },
Item { weight: 11, value: 23 },
Item { weight: 8, value: 15 },
Item { weight: 9, value: 16 }
],
KnapsackSolution {
optimal_profit: 51,
total_weight: 26,
item_indices: vec![2, 3, 4]
}
),
test_basic_knapsack_medium: (
190,
vec![
Item { weight: 56, value: 50 },
Item { weight: 59, value: 50 },
Item { weight: 80, value: 64 },
Item { weight: 64, value: 46 },
Item { weight: 75, value: 50 },
Item { weight: 17, value: 5 }
],
KnapsackSolution {
optimal_profit: 150,
total_weight: 190,
item_indices: vec![1, 2, 5]
}
),
test_diverse_weights_values_small: (
50,
vec![
Item { weight: 31, value: 70 },
Item { weight: 10, value: 20 },
Item { weight: 20, value: 39 },
Item { weight: 19, value: 37 },
Item { weight: 4, value: 7 },
Item { weight: 3, value: 5 },
Item { weight: 6, value: 10 }
],
KnapsackSolution {
optimal_profit: 107,
total_weight: 50,
item_indices: vec![1, 4]
}
),
test_diverse_weights_values_medium: (
104,
vec![
Item { weight: 25, value: 350 },
Item { weight: 35, value: 400 },
Item { weight: 45, value: 450 },
Item { weight: 5, value: 20 },
Item { weight: 25, value: 70 },
Item { weight: 3, value: 8 },
Item { weight: 2, value: 5 },
Item { weight: 2, value: 5 }
],
KnapsackSolution {
optimal_profit: 900,
total_weight: 104,
item_indices: vec![1, 3, 4, 5, 7, 8]
}
),
test_high_value_items: (
170,
vec![
Item { weight: 41, value: 442 },
Item { weight: 50, value: 525 },
Item { weight: 49, value: 511 },
Item { weight: 59, value: 593 },
Item { weight: 55, value: 546 },
Item { weight: 57, value: 564 },
Item { weight: 60, value: 617 }
],
KnapsackSolution {
optimal_profit: 1735,
total_weight: 169,
item_indices: vec![2, 4, 7]
}
),
test_large_knapsack: (
750,
vec![
Item { weight: 70, value: 135 },
Item { weight: 73, value: 139 },
Item { weight: 77, value: 149 },
Item { weight: 80, value: 150 },
Item { weight: 82, value: 156 },
Item { weight: 87, value: 163 },
Item { weight: 90, value: 173 },
Item { weight: 94, value: 184 },
Item { weight: 98, value: 192 },
Item { weight: 106, value: 201 },
Item { weight: 110, value: 210 },
Item { weight: 113, value: 214 },
Item { weight: 115, value: 221 },
Item { weight: 118, value: 229 },
Item { weight: 120, value: 240 }
],
KnapsackSolution {
optimal_profit: 1458,
total_weight: 749,
item_indices: vec![1, 3, 5, 7, 8, 9, 14, 15]
}
),
test_zero_capacity: (
0,
vec![
Item { weight: 1, value: 1 },
Item { weight: 2, value: 2 },
Item { weight: 3, value: 3 }
],
KnapsackSolution {
optimal_profit: 0,
total_weight: 0,
item_indices: vec![]
}
),
test_very_small_capacity: (
1,
vec![
Item { weight: 10, value: 1 },
Item { weight: 20, value: 2 },
Item { weight: 30, value: 3 }
],
KnapsackSolution {
optimal_profit: 0,
total_weight: 0,
item_indices: vec![]
}
),
test_no_items: (
1,
vec![],
KnapsackSolution {
optimal_profit: 0,
total_weight: 0,
item_indices: vec![]
}
),
test_item_too_heavy: (
1,
vec![
Item { weight: 2, value: 100 }
],
KnapsackSolution {
optimal_profit: 0,
total_weight: 0,
item_indices: vec![]
}
),
test_greedy_algorithm_does_not_work: (
10,
vec![
Item { weight: 10, value: 15 },
Item { weight: 6, value: 7 },
Item { weight: 4, value: 9 }
],
KnapsackSolution {
optimal_profit: 16,
total_weight: 10,
item_indices: vec![2, 3]
}
),
test_greedy_algorithm_does_not_work_weight_smaller_than_capacity: (
10,
vec![
Item { weight: 10, value: 15 },
Item { weight: 1, value: 9 },
Item { weight: 2, value: 7 }
],
KnapsackSolution {
optimal_profit: 16,
total_weight: 3,
item_indices: vec![2, 3]
}
),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/longest_increasing_subsequence.rs | src/dynamic_programming/longest_increasing_subsequence.rs | /// Finds the longest increasing subsequence and returns it.
///
/// If multiple subsequences with the longest possible subsequence length can be found, the
/// subsequence which appeared first will be returned (see `test_example_1`).
///
/// Inspired by [this LeetCode problem](https://leetcode.com/problems/longest-increasing-subsequence/).
pub fn longest_increasing_subsequence<T: Ord + Clone>(input_array: &[T]) -> Vec<T> {
let n = input_array.len();
if n <= 1 {
return input_array.to_vec();
}
let mut increasing_sequence: Vec<(T, usize)> = Vec::new();
let mut previous = vec![0_usize; n];
increasing_sequence.push((input_array[0].clone(), 1));
for i in 1..n {
let value = input_array[i].clone();
if value > increasing_sequence.last().unwrap().0 {
previous[i] = increasing_sequence.last().unwrap().1 - 1;
increasing_sequence.push((value, i + 1));
continue;
}
let change_position = increasing_sequence
.binary_search(&(value.clone(), 0))
.unwrap_or_else(|x| x);
increasing_sequence[change_position] = (value, i + 1);
previous[i] = match change_position {
0 => i,
other => increasing_sequence[other - 1].1 - 1,
};
}
// Construct subsequence
let mut out: Vec<T> = Vec::with_capacity(increasing_sequence.len());
out.push(increasing_sequence.last().unwrap().0.clone());
let mut current_index = increasing_sequence.last().unwrap().1 - 1;
while previous[current_index] != current_index {
current_index = previous[current_index];
out.push(input_array[current_index].clone());
}
out.into_iter().rev().collect()
}
#[cfg(test)]
mod tests {
use super::longest_increasing_subsequence;
#[test]
/// Need to specify generic type T in order to function
fn test_empty_vec() {
assert_eq!(longest_increasing_subsequence::<i32>(&[]), vec![]);
}
#[test]
fn test_example_1() {
assert_eq!(
longest_increasing_subsequence(&[10, 9, 2, 5, 3, 7, 101, 18]),
vec![2, 3, 7, 18]
);
}
#[test]
fn test_example_2() {
assert_eq!(
longest_increasing_subsequence(&[0, 1, 0, 3, 2, 3]),
vec![0, 1, 2, 3]
);
}
#[test]
fn test_example_3() {
assert_eq!(
longest_increasing_subsequence(&[7, 7, 7, 7, 7, 7, 7]),
vec![7]
);
}
#[test]
fn test_tle() {
let mut input_array = vec![0i64; 1e5 as usize];
let mut expected_result: Vec<i64> = Vec::with_capacity(5e4 as usize);
for (idx, num) in input_array.iter_mut().enumerate() {
match idx % 2 {
0 => {
*num = idx as i64;
expected_result.push(*num);
}
1 => *num = -(idx as i64),
_ => unreachable!(),
}
}
expected_result[0] = -1;
assert_eq!(
longest_increasing_subsequence(&input_array),
expected_result
);
// should be [-1, 2, 4, 6, 8, ...]
// the first number is not 0, it would be replaced by -1 before 2 is added
}
#[test]
fn test_negative_elements() {
assert_eq!(longest_increasing_subsequence(&[-2, -1]), vec![-2, -1]);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/trapped_rainwater.rs | src/dynamic_programming/trapped_rainwater.rs | //! Module to calculate trapped rainwater in an elevation map.
/// Computes the total volume of trapped rainwater in a given elevation map.
///
/// # Arguments
///
/// * `elevation_map` - A slice containing the heights of the terrain elevations.
///
/// # Returns
///
/// The total volume of trapped rainwater.
pub fn trapped_rainwater(elevation_map: &[u32]) -> u32 {
let left_max = calculate_max_values(elevation_map, false);
let right_max = calculate_max_values(elevation_map, true);
let mut water_trapped = 0;
// Calculate trapped water
for i in 0..elevation_map.len() {
water_trapped += left_max[i].min(right_max[i]) - elevation_map[i];
}
water_trapped
}
/// Determines the maximum heights from either direction in the elevation map.
///
/// # Arguments
///
/// * `elevation_map` - A slice representing the heights of the terrain elevations.
/// * `reverse` - A boolean that indicates the direction of calculation.
/// - `false` for left-to-right.
/// - `true` for right-to-left.
///
/// # Returns
///
/// A vector containing the maximum heights encountered up to each position.
fn calculate_max_values(elevation_map: &[u32], reverse: bool) -> Vec<u32> {
let mut max_values = vec![0; elevation_map.len()];
let mut current_max = 0;
for i in create_iter(elevation_map.len(), reverse) {
current_max = current_max.max(elevation_map[i]);
max_values[i] = current_max;
}
max_values
}
/// Creates an iterator for the given length, optionally reversing it.
///
/// # Arguments
///
/// * `len` - The length of the iterator.
/// * `reverse` - A boolean that determines the order of iteration.
/// - `false` for forward iteration.
/// - `true` for reverse iteration.
///
/// # Returns
///
/// A boxed iterator that iterates over the range of indices.
fn create_iter(len: usize, reverse: bool) -> Box<dyn Iterator<Item = usize>> {
if reverse {
Box::new((0..len).rev())
} else {
Box::new(0..len)
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! trapped_rainwater_tests {
($($name:ident: $test_case:expr,)*) => {
$(
#[test]
fn $name() {
let (elevation_map, expected_trapped_water) = $test_case;
assert_eq!(trapped_rainwater(&elevation_map), expected_trapped_water);
let elevation_map_rev: Vec<u32> = elevation_map.iter().rev().cloned().collect();
assert_eq!(trapped_rainwater(&elevation_map_rev), expected_trapped_water);
}
)*
};
}
trapped_rainwater_tests! {
test_trapped_rainwater_basic: (
[0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1],
6
),
test_trapped_rainwater_peak_under_water: (
[3, 0, 2, 0, 4],
7,
),
test_bucket: (
[5, 1, 5],
4
),
test_skewed_bucket: (
[4, 1, 5],
3
),
test_trapped_rainwater_empty: (
[],
0
),
test_trapped_rainwater_flat: (
[0, 0, 0, 0, 0],
0
),
test_trapped_rainwater_no_trapped_water: (
[1, 1, 2, 4, 0, 0, 0],
0
),
test_trapped_rainwater_single_elevation_map: (
[5],
0
),
test_trapped_rainwater_two_point_elevation_map: (
[5, 1],
0
),
test_trapped_rainwater_large_elevation_map_difference: (
[5, 1, 6, 1, 7, 1, 8],
15
),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/longest_common_subsequence.rs | src/dynamic_programming/longest_common_subsequence.rs | //! This module implements the Longest Common Subsequence (LCS) algorithm.
//! The LCS problem is finding the longest subsequence common to two sequences.
//! It differs from the problem of finding common substrings: unlike substrings, subsequences
//! are not required to occupy consecutive positions within the original sequences.
//! This implementation handles Unicode strings efficiently and correctly, ensuring
//! that multi-byte characters are managed properly.
/// Computes the longest common subsequence of two input strings.
///
/// The longest common subsequence (LCS) of two strings is the longest sequence that can
/// be derived from both strings by deleting some elements without changing the order of
/// the remaining elements.
///
/// ## Note
/// The function may return different LCSs for the same pair of strings depending on the
/// order of the inputs and the nature of the sequences. This is due to the way the dynamic
/// programming algorithm resolves ties when multiple common subsequences of the same length
/// exist. The order of the input strings can influence the specific path taken through the
/// DP table, resulting in different valid LCS outputs.
///
/// For example:
/// `longest_common_subsequence("hello, world!", "world, hello!")` returns `"hello!"`
/// but
/// `longest_common_subsequence("world, hello!", "hello, world!")` returns `"world!"`
///
/// This difference arises because the dynamic programming table is filled differently based
/// on the input order, leading to different tie-breaking decisions and thus different LCS results.
pub fn longest_common_subsequence(first_seq: &str, second_seq: &str) -> String {
let first_seq_chars = first_seq.chars().collect::<Vec<char>>();
let second_seq_chars = second_seq.chars().collect::<Vec<char>>();
let lcs_lengths = initialize_lcs_lengths(&first_seq_chars, &second_seq_chars);
let lcs_chars = reconstruct_lcs(&first_seq_chars, &second_seq_chars, &lcs_lengths);
lcs_chars.into_iter().collect()
}
fn initialize_lcs_lengths(first_seq_chars: &[char], second_seq_chars: &[char]) -> Vec<Vec<usize>> {
let first_seq_len = first_seq_chars.len();
let second_seq_len = second_seq_chars.len();
let mut lcs_lengths = vec![vec![0; second_seq_len + 1]; first_seq_len + 1];
// Populate the LCS lengths table
(1..=first_seq_len).for_each(|i| {
(1..=second_seq_len).for_each(|j| {
lcs_lengths[i][j] = if first_seq_chars[i - 1] == second_seq_chars[j - 1] {
lcs_lengths[i - 1][j - 1] + 1
} else {
lcs_lengths[i - 1][j].max(lcs_lengths[i][j - 1])
};
});
});
lcs_lengths
}
fn reconstruct_lcs(
first_seq_chars: &[char],
second_seq_chars: &[char],
lcs_lengths: &[Vec<usize>],
) -> Vec<char> {
let mut lcs_chars = Vec::new();
let mut i = first_seq_chars.len();
let mut j = second_seq_chars.len();
while i > 0 && j > 0 {
if first_seq_chars[i - 1] == second_seq_chars[j - 1] {
lcs_chars.push(first_seq_chars[i - 1]);
i -= 1;
j -= 1;
} else if lcs_lengths[i - 1][j] >= lcs_lengths[i][j - 1] {
i -= 1;
} else {
j -= 1;
}
}
lcs_chars.reverse();
lcs_chars
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! longest_common_subsequence_tests {
($($name:ident: $test_case:expr,)*) => {
$(
#[test]
fn $name() {
let (first_seq, second_seq, expected_lcs) = $test_case;
assert_eq!(longest_common_subsequence(&first_seq, &second_seq), expected_lcs);
}
)*
};
}
longest_common_subsequence_tests! {
empty_case: ("", "", ""),
one_empty: ("", "abcd", ""),
identical_strings: ("abcd", "abcd", "abcd"),
completely_different: ("abcd", "efgh", ""),
single_character: ("a", "a", "a"),
different_length: ("abcd", "abc", "abc"),
special_characters: ("$#%&", "#@!%", "#%"),
long_strings: ("abcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefgh",
"bcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefgha",
"bcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefgh"),
unicode_characters: ("你好,世界", "再见,世界", ",世界"),
spaces_and_punctuation_0: ("hello, world!", "world, hello!", "hello!"),
spaces_and_punctuation_1: ("hello, world!", "world, hello!", "hello!"), // longest_common_subsequence is not symmetric
random_case_1: ("abcdef", "xbcxxxe", "bce"),
random_case_2: ("xyz", "abc", ""),
random_case_3: ("abracadabra", "avadakedavra", "aaadara"),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/is_subsequence.rs | src/dynamic_programming/is_subsequence.rs | //! A module for checking if one string is a subsequence of another string.
//!
//! A subsequence is formed by deleting some (can be none) of the characters
//! from the original string without disturbing the relative positions of the
//! remaining characters. This module provides a function to determine if
//! a given string is a subsequence of another string.
/// Checks if `sub` is a subsequence of `main`.
///
/// # Arguments
///
/// * `sub` - A string slice that may be a subsequence.
/// * `main` - A string slice that is checked against.
///
/// # Returns
///
/// Returns `true` if `sub` is a subsequence of `main`, otherwise returns `false`.
pub fn is_subsequence(sub: &str, main: &str) -> bool {
let mut sub_iter = sub.chars().peekable();
let mut main_iter = main.chars();
while let Some(&sub_char) = sub_iter.peek() {
match main_iter.next() {
Some(main_char) if main_char == sub_char => {
sub_iter.next();
}
None => return false,
_ => {}
}
}
true
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! subsequence_tests {
($($name:ident: $test_case:expr,)*) => {
$(
#[test]
fn $name() {
let (sub, main, expected) = $test_case;
assert_eq!(is_subsequence(sub, main), expected);
}
)*
};
}
subsequence_tests! {
test_empty_subsequence: ("", "ahbgdc", true),
test_empty_strings: ("", "", true),
test_non_empty_sub_empty_main: ("abc", "", false),
test_subsequence_found: ("abc", "ahbgdc", true),
test_subsequence_not_found: ("axc", "ahbgdc", false),
test_longer_sub: ("abcd", "abc", false),
test_single_character_match: ("a", "ahbgdc", true),
test_single_character_not_match: ("x", "ahbgdc", false),
test_subsequence_at_start: ("abc", "abchello", true),
test_subsequence_at_end: ("cde", "abcde", true),
test_same_characters: ("aaa", "aaaaa", true),
test_interspersed_subsequence: ("ace", "abcde", true),
test_different_chars_in_subsequence: ("aceg", "abcdef", false),
test_single_character_in_main_not_match: ("a", "b", false),
test_single_character_in_main_match: ("b", "b", true),
test_subsequence_with_special_chars: ("a1!c", "a1!bcd", true),
test_case_sensitive: ("aBc", "abc", false),
test_subsequence_with_whitespace: ("hello world", "h e l l o w o r l d", true),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/longest_continuous_increasing_subsequence.rs | src/dynamic_programming/longest_continuous_increasing_subsequence.rs | use std::cmp::Ordering;
/// Finds the longest continuous increasing subsequence in a slice.
///
/// Given a slice of elements, this function returns a slice representing
/// the longest continuous subsequence where each element is strictly
/// less than the following element.
///
/// # Arguments
///
/// * `arr` - A reference to a slice of elements
///
/// # Returns
///
/// A subslice of the input, representing the longest continuous increasing subsequence.
/// If there are multiple subsequences of the same length, the function returns the first one found.
pub fn longest_continuous_increasing_subsequence<T: Ord>(arr: &[T]) -> &[T] {
if arr.len() <= 1 {
return arr;
}
let mut start = 0;
let mut max_start = 0;
let mut max_len = 1;
let mut curr_len = 1;
for i in 1..arr.len() {
match arr[i - 1].cmp(&arr[i]) {
// include current element is greater than or equal to the previous
// one elements in the current increasing sequence
Ordering::Less | Ordering::Equal => {
curr_len += 1;
}
// reset when a strictly decreasing element is found
Ordering::Greater => {
if curr_len > max_len {
max_len = curr_len;
max_start = start;
}
// reset start to the current position
start = i;
// reset current length
curr_len = 1;
}
}
}
// final check for the last sequence
if curr_len > max_len {
max_len = curr_len;
max_start = start;
}
&arr[max_start..max_start + max_len]
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_cases {
($($name:ident: $test_case:expr,)*) => {
$(
#[test]
fn $name() {
let (input, expected) = $test_case;
assert_eq!(longest_continuous_increasing_subsequence(input), expected);
}
)*
};
}
test_cases! {
empty_array: (&[] as &[isize], &[] as &[isize]),
single_element: (&[1], &[1]),
all_increasing: (&[1, 2, 3, 4, 5], &[1, 2, 3, 4, 5]),
all_decreasing: (&[5, 4, 3, 2, 1], &[5]),
with_equal_elements: (&[1, 2, 2, 3, 4, 2], &[1, 2, 2, 3, 4]),
increasing_with_plateau: (&[1, 2, 2, 2, 3, 3, 4], &[1, 2, 2, 2, 3, 3, 4]),
mixed_elements: (&[5, 4, 3, 4, 2, 1], &[3, 4]),
alternating_increase_decrease: (&[1, 2, 1, 2, 1, 2], &[1, 2]),
zigzag: (&[1, 3, 2, 4, 3, 5], &[1, 3]),
single_negative_element: (&[-1], &[-1]),
negative_and_positive_mixed: (&[-2, -1, 0, 1, 2, 3], &[-2, -1, 0, 1, 2, 3]),
increasing_then_decreasing: (&[1, 2, 3, 4, 3, 2, 1], &[1, 2, 3, 4]),
single_increasing_subsequence_later: (&[3, 2, 1, 1, 2, 3, 4], &[1, 1, 2, 3, 4]),
longer_subsequence_at_start: (&[5, 6, 7, 8, 9, 2, 3, 4, 5], &[5, 6, 7, 8, 9]),
longer_subsequence_at_end: (&[2, 3, 4, 10, 5, 6, 7, 8, 9], &[5, 6, 7, 8, 9]),
longest_subsequence_at_start: (&[2, 3, 4, 5, 1, 0], &[2, 3, 4, 5]),
longest_subsequence_at_end: (&[1, 7, 2, 3, 4, 5,], &[2, 3, 4, 5]),
repeated_elements: (&[1, 1, 1, 1, 1], &[1, 1, 1, 1, 1]),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/subset_sum.rs | src/dynamic_programming/subset_sum.rs | //! This module provides a solution to the subset sum problem using dynamic programming.
//!
//! # Complexity
//! - Time complexity: O(n * sum) where n is array length and sum is the target sum
//! - Space complexity: O(n * sum) for the DP table
/// Determines if there exists a subset of the given array that sums to the target value.
/// Uses dynamic programming to solve the subset sum problem.
///
/// # Arguments
/// * `arr` - A slice of integers representing the input array.
/// * `required_sum` - The target sum to check for.
///
/// # Returns
/// * `bool` - A boolean indicating whether a subset exists that sums to the target.
pub fn is_sum_subset(arr: &[i32], required_sum: i32) -> bool {
let n = arr.len();
// Handle edge case where required sum is 0 (empty subset always sums to 0)
if required_sum == 0 {
return true;
}
// Handle edge case where array is empty but required sum is positive
if n == 0 && required_sum > 0 {
return false;
}
// dp[i][j] stores whether sum j can be achieved using first i elements
let mut dp = vec![vec![false; required_sum as usize + 1]; n + 1];
// Base case: sum 0 can always be achieved with any number of elements (empty subset)
for i in 0..=n {
dp[i][0] = true;
}
// Base case: with 0 elements, no positive sum can be achieved
for j in 1..=required_sum as usize {
dp[0][j] = false;
}
// Fill the DP table
for i in 1..=n {
for j in 1..=required_sum as usize {
if arr[i - 1] > j as i32 {
// Current element is too large, exclude it
dp[i][j] = dp[i - 1][j];
} else {
// Either exclude the current element or include it
dp[i][j] = dp[i - 1][j] || dp[i - 1][j - arr[i - 1] as usize];
}
}
}
dp[n][required_sum as usize]
}
#[cfg(test)]
mod tests {
use super::*;
// Macro to generate multiple test cases for the is_sum_subset function
macro_rules! subset_sum_tests {
($($name:ident: $input:expr => $expected:expr,)*) => {
$(
#[test]
fn $name() {
let (arr, sum) = $input;
assert_eq!(is_sum_subset(arr, sum), $expected);
}
)*
};
}
subset_sum_tests! {
// Common test cases
test_case_1: (&[2, 4, 6, 8], 5) => false,
test_case_2: (&[2, 4, 6, 8], 14) => true,
test_case_3: (&[3, 34, 4, 12, 5, 2], 9) => true,
test_case_4: (&[3, 34, 4, 12, 5, 2], 30) => false,
test_case_5: (&[1, 2, 3, 4, 5], 15) => true,
// Edge test cases
test_case_empty_array_positive_sum: (&[], 5) => false,
test_case_empty_array_zero_sum: (&[], 0) => true,
test_case_zero_sum: (&[1, 2, 3], 0) => true,
test_case_single_element_match: (&[5], 5) => true,
test_case_single_element_no_match: (&[3], 5) => false,
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/longest_common_substring.rs | src/dynamic_programming/longest_common_substring.rs | //! This module provides a function to find the length of the longest common substring
//! between two strings using dynamic programming.
/// Finds the length of the longest common substring between two strings using dynamic programming.
///
/// The algorithm uses a 2D dynamic programming table where each cell represents
/// the length of the longest common substring ending at the corresponding indices in
/// the two input strings. The maximum value in the DP table is the result, i.e., the
/// length of the longest common substring.
///
/// The time complexity is `O(n * m)`, where `n` and `m` are the lengths of the two strings.
/// # Arguments
///
/// * `s1` - The first input string.
/// * `s2` - The second input string.
///
/// # Returns
///
/// Returns the length of the longest common substring between `s1` and `s2`.
pub fn longest_common_substring(s1: &str, s2: &str) -> usize {
let mut substr_len = vec![vec![0; s2.len() + 1]; s1.len() + 1];
let mut max_len = 0;
s1.as_bytes().iter().enumerate().for_each(|(i, &c1)| {
s2.as_bytes().iter().enumerate().for_each(|(j, &c2)| {
if c1 == c2 {
substr_len[i + 1][j + 1] = substr_len[i][j] + 1;
max_len = max_len.max(substr_len[i + 1][j + 1]);
}
});
});
max_len
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_longest_common_substring {
($($name:ident: $inputs:expr,)*) => {
$(
#[test]
fn $name() {
let (s1, s2, expected) = $inputs;
assert_eq!(longest_common_substring(s1, s2), expected);
assert_eq!(longest_common_substring(s2, s1), expected);
}
)*
}
}
test_longest_common_substring! {
test_empty_strings: ("", "", 0),
test_one_empty_string: ("", "a", 0),
test_identical_single_char: ("a", "a", 1),
test_different_single_char: ("a", "b", 0),
test_common_substring_at_start: ("abcdef", "abc", 3),
test_common_substring_at_middle: ("abcdef", "bcd", 3),
test_common_substring_at_end: ("abcdef", "def", 3),
test_no_common_substring: ("abc", "xyz", 0),
test_overlapping_substrings: ("abcdxyz", "xyzabcd", 4),
test_special_characters: ("@abc#def$", "#def@", 4),
test_case_sensitive: ("abcDEF", "ABCdef", 0),
test_full_string_match: ("GeeksforGeeks", "GeeksforGeeks", 13),
test_substring_with_repeated_chars: ("aaaaaaaaaaaaa", "aaa", 3),
test_longer_strings_with_common_substring: ("OldSite:GeeksforGeeks.org", "NewSite:GeeksQuiz.com", 10),
test_no_common_substring_with_special_chars: ("!!!", "???", 0),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/maximum_subarray.rs | src/dynamic_programming/maximum_subarray.rs | //! This module provides a function to find the largest sum of the subarray
//! in a given array of integers using dynamic programming. It also includes
//! tests to verify the correctness of the implementation.
/// Custom error type for maximum subarray
#[derive(Debug, PartialEq)]
pub enum MaximumSubarrayError {
EmptyArray,
}
/// Finds the subarray (containing at least one number) which has the largest sum
/// and returns its sum.
///
/// A subarray is a contiguous part of an array.
///
/// # Arguments
///
/// * `array` - A slice of integers.
///
/// # Returns
///
/// A `Result` which is:
/// * `Ok(isize)` representing the largest sum of a contiguous subarray.
/// * `Err(MaximumSubarrayError)` if the array is empty.
///
/// # Complexity
///
/// * Time complexity: `O(array.len())`
/// * Space complexity: `O(1)`
pub fn maximum_subarray(array: &[isize]) -> Result<isize, MaximumSubarrayError> {
if array.is_empty() {
return Err(MaximumSubarrayError::EmptyArray);
}
let mut cur_sum = array[0];
let mut max_sum = cur_sum;
for &x in &array[1..] {
cur_sum = (cur_sum + x).max(x);
max_sum = max_sum.max(cur_sum);
}
Ok(max_sum)
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! maximum_subarray_tests {
($($name:ident: $tc:expr,)*) => {
$(
#[test]
fn $name() {
let (array, expected) = $tc;
assert_eq!(maximum_subarray(&array), expected);
}
)*
}
}
maximum_subarray_tests! {
test_all_non_negative: (vec![1, 0, 5, 8], Ok(14)),
test_all_negative: (vec![-3, -1, -8, -2], Ok(-1)),
test_mixed_negative_and_positive: (vec![-4, 3, -2, 5, -8], Ok(6)),
test_single_element_positive: (vec![6], Ok(6)),
test_single_element_negative: (vec![-6], Ok(-6)),
test_mixed_elements: (vec![-2, 1, -3, 4, -1, 2, 1, -5, 4], Ok(6)),
test_empty_array: (vec![], Err(MaximumSubarrayError::EmptyArray)),
test_all_zeroes: (vec![0, 0, 0, 0], Ok(0)),
test_single_zero: (vec![0], Ok(0)),
test_alternating_signs: (vec![3, -2, 5, -1], Ok(6)),
test_all_negatives_with_one_positive: (vec![-3, -4, 1, -7, -2], Ok(1)),
test_all_positives_with_one_negative: (vec![3, 4, -1, 7, 2], Ok(15)),
test_all_positives: (vec![2, 3, 1, 5], Ok(11)),
test_large_values: (vec![1000, -500, 1000, -500, 1000], Ok(2000)),
test_large_array: ((0..1000).collect::<Vec<_>>(), Ok(499500)),
test_large_negative_array: ((0..1000).map(|x| -x).collect::<Vec<_>>(), Ok(0)),
test_single_large_positive: (vec![1000000], Ok(1000000)),
test_single_large_negative: (vec![-1000000], Ok(-1000000)),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/smith_waterman.rs | src/dynamic_programming/smith_waterman.rs | //! This module contains the Smith-Waterman algorithm implementation for local sequence alignment.
//!
//! The Smith-Waterman algorithm is a dynamic programming algorithm used for determining
//! similar regions between two sequences (nucleotide or protein sequences). It is particularly
//! useful in bioinformatics for identifying optimal local alignments.
//!
//! # Algorithm Overview
//!
//! The algorithm works by:
//! 1. Creating a scoring matrix where each cell represents the maximum alignment score
//! ending at that position
//! 2. Using match, mismatch, and gap penalties to calculate scores
//! 3. Allowing scores to reset to 0 (ensuring local rather than global alignment)
//! 4. Tracing back from the highest scoring position to reconstruct the alignment
//!
//! # Time Complexity
//!
//! O(m * n) where m and n are the lengths of the two sequences
//!
//! # Space Complexity
//!
//! O(m * n) for the scoring matrix
//!
//! # References
//!
//! - [Smith, T.F., Waterman, M.S. (1981). "Identification of Common Molecular Subsequences"](https://doi.org/10.1016/0022-2836(81)90087-5)
//! - [Wikipedia: Smith-Waterman algorithm](https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm)
use std::cmp::max;
/// Calculates the score for a character pair based on match, mismatch, or gap scoring.
///
/// # Arguments
///
/// * `source_char` - Character from the source sequence
/// * `target_char` - Character from the target sequence
/// * `match_score` - Score awarded for matching characters (typically positive)
/// * `mismatch_score` - Score penalty for mismatching characters (typically negative)
/// * `gap_score` - Score penalty for gaps (typically negative)
///
/// # Returns
///
/// The calculated score for the character pair
///
/// # Examples
///
/// ```
/// use the_algorithms_rust::dynamic_programming::score_function;
///
/// let score = score_function('A', 'A', 1, -1, -2);
/// assert_eq!(score, 1); // Match
///
/// let score = score_function('A', 'C', 1, -1, -2);
/// assert_eq!(score, -1); // Mismatch
///
/// let score = score_function('-', 'A', 1, -1, -2);
/// assert_eq!(score, -2); // Gap
/// ```
pub fn score_function(
source_char: char,
target_char: char,
match_score: i32,
mismatch_score: i32,
gap_score: i32,
) -> i32 {
if source_char == '-' || target_char == '-' {
gap_score
} else if source_char == target_char {
match_score
} else {
mismatch_score
}
}
/// Performs the Smith-Waterman local sequence alignment algorithm.
///
/// This function creates a scoring matrix using dynamic programming to find the
/// optimal local alignment between two sequences. The algorithm is case-insensitive.
///
/// # Arguments
///
/// * `query` - The query sequence (e.g., DNA, protein)
/// * `subject` - The subject sequence to align against
/// * `match_score` - Score for matching characters (default: 1)
/// * `mismatch_score` - Penalty for mismatching characters (default: -1)
/// * `gap_score` - Penalty for gaps/indels (default: -2)
///
/// # Returns
///
/// A 2D vector representing the dynamic programming scoring matrix
///
/// # Examples
///
/// ```
/// use the_algorithms_rust::dynamic_programming::smith_waterman;
///
/// let score_matrix = smith_waterman("ACAC", "CA", 1, -1, -2);
/// assert_eq!(score_matrix.len(), 5); // query length + 1
/// assert_eq!(score_matrix[0].len(), 3); // subject length + 1
/// ```
pub fn smith_waterman(
query: &str,
subject: &str,
match_score: i32,
mismatch_score: i32,
gap_score: i32,
) -> Vec<Vec<i32>> {
let query_upper: Vec<char> = query.to_uppercase().chars().collect();
let subject_upper: Vec<char> = subject.to_uppercase().chars().collect();
let m = query_upper.len();
let n = subject_upper.len();
// Initialize scoring matrix with zeros
let mut score = vec![vec![0; n + 1]; m + 1];
// Fill the scoring matrix using dynamic programming
for i in 1..=m {
for j in 1..=n {
// Calculate score for match/mismatch
let match_or_mismatch = score[i - 1][j - 1]
+ score_function(
query_upper[i - 1],
subject_upper[j - 1],
match_score,
mismatch_score,
gap_score,
);
// Calculate score for deletion (gap in subject)
let delete = score[i - 1][j] + gap_score;
// Calculate score for insertion (gap in query)
let insert = score[i][j - 1] + gap_score;
// Take maximum of all options, but never go below 0 (local alignment)
score[i][j] = max(0, max(match_or_mismatch, max(delete, insert)));
}
}
score
}
/// Performs traceback on the Smith-Waterman score matrix to reconstruct the optimal alignment.
///
/// This function starts from the highest scoring cell and traces back through the matrix
/// to reconstruct the aligned sequences. The traceback stops when a cell with score 0
/// is encountered.
///
/// # Arguments
///
/// * `score` - The score matrix from the Smith-Waterman algorithm
/// * `query` - Original query sequence used in alignment
/// * `subject` - Original subject sequence used in alignment
/// * `match_score` - Score for matching characters (should match smith_waterman call)
/// * `mismatch_score` - Score for mismatching characters (should match smith_waterman call)
/// * `gap_score` - Penalty for gaps (should match smith_waterman call)
///
/// # Returns
///
/// A String containing the two aligned sequences separated by a newline,
/// or an empty string if no significant alignment is found
///
/// # Examples
///
/// ```
/// use the_algorithms_rust::dynamic_programming::{smith_waterman, traceback};
///
/// let score_matrix = smith_waterman("ACAC", "CA", 1, -1, -2);
/// let alignment = traceback(&score_matrix, "ACAC", "CA", 1, -1, -2);
/// assert_eq!(alignment, "CA\nCA");
/// ```
pub fn traceback(
score: &[Vec<i32>],
query: &str,
subject: &str,
match_score: i32,
mismatch_score: i32,
gap_score: i32,
) -> String {
let query_upper: Vec<char> = query.to_uppercase().chars().collect();
let subject_upper: Vec<char> = subject.to_uppercase().chars().collect();
// Find the cell with maximum score
let mut max_value = 0;
let (mut i_max, mut j_max) = (0, 0);
for (i, row) in score.iter().enumerate() {
for (j, &value) in row.iter().enumerate() {
if value > max_value {
max_value = value;
i_max = i;
j_max = j;
}
}
}
// If no significant alignment found, return empty string
if max_value <= 0 {
return String::new();
}
// Traceback from the maximum scoring cell
let (mut i, mut j) = (i_max, j_max);
let mut align1 = Vec::new();
let mut align2 = Vec::new();
// Continue tracing back until we hit a cell with score 0
while i > 0 && j > 0 && score[i][j] > 0 {
let current_score = score[i][j];
// Check if we came from diagonal (match/mismatch)
if current_score
== score[i - 1][j - 1]
+ score_function(
query_upper[i - 1],
subject_upper[j - 1],
match_score,
mismatch_score,
gap_score,
)
{
align1.push(query_upper[i - 1]);
align2.push(subject_upper[j - 1]);
i -= 1;
j -= 1;
}
// Check if we came from above (deletion/gap in subject)
else if current_score == score[i - 1][j] + gap_score {
align1.push(query_upper[i - 1]);
align2.push('-');
i -= 1;
}
// Otherwise we came from left (insertion/gap in query)
else {
align1.push('-');
align2.push(subject_upper[j - 1]);
j -= 1;
}
}
// Reverse the sequences (we built them backwards)
align1.reverse();
align2.reverse();
format!(
"{}\n{}",
align1.into_iter().collect::<String>(),
align2.into_iter().collect::<String>()
)
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! smith_waterman_tests {
($($name:ident: $test_cases:expr,)*) => {
$(
#[test]
fn $name() {
let (query, subject, match_score, mismatch_score, gap_score, expected) = $test_cases;
assert_eq!(smith_waterman(query, subject, match_score, mismatch_score, gap_score), expected);
}
)*
}
}
macro_rules! traceback_tests {
($($name:ident: $test_cases:expr,)*) => {
$(
#[test]
fn $name() {
let (score, query, subject, match_score, mismatch_score, gap_score, expected) = $test_cases;
assert_eq!(traceback(&score, query, subject, match_score, mismatch_score, gap_score), expected);
}
)*
}
}
smith_waterman_tests! {
test_acac_ca: ("ACAC", "CA", 1, -1, -2, vec![
vec![0, 0, 0],
vec![0, 0, 1],
vec![0, 1, 0],
vec![0, 0, 2],
vec![0, 1, 0],
]),
test_agt_agt: ("AGT", "AGT", 1, -1, -2, vec![
vec![0, 0, 0, 0],
vec![0, 1, 0, 0],
vec![0, 0, 2, 0],
vec![0, 0, 0, 3],
]),
test_agt_gta: ("AGT", "GTA", 1, -1, -2, vec![
vec![0, 0, 0, 0],
vec![0, 0, 0, 1],
vec![0, 1, 0, 0],
vec![0, 0, 2, 0],
]),
test_agt_g: ("AGT", "G", 1, -1, -2, vec![
vec![0, 0],
vec![0, 0],
vec![0, 1],
vec![0, 0],
]),
test_g_agt: ("G", "AGT", 1, -1, -2, vec![
vec![0, 0, 0, 0],
vec![0, 0, 1, 0],
]),
test_empty_query: ("", "CA", 1, -1, -2, vec![vec![0, 0, 0]]),
test_empty_subject: ("ACAC", "", 1, -1, -2, vec![vec![0], vec![0], vec![0], vec![0], vec![0]]),
test_both_empty: ("", "", 1, -1, -2, vec![vec![0]]),
}
traceback_tests! {
test_traceback_acac_ca: (
vec![
vec![0, 0, 0],
vec![0, 0, 1],
vec![0, 1, 0],
vec![0, 0, 2],
vec![0, 1, 0],
],
"ACAC",
"CA",
1, -1, -2,
"CA\nCA",
),
test_traceback_agt_agt: (
vec![
vec![0, 0, 0, 0],
vec![0, 1, 0, 0],
vec![0, 0, 2, 0],
vec![0, 0, 0, 3],
],
"AGT",
"AGT",
1, -1, -2,
"AGT\nAGT",
),
test_traceback_empty: (vec![vec![0, 0, 0]], "ACAC", "", 1, -1, -2, ""),
test_traceback_custom_scoring: (
vec![
vec![0, 0, 0],
vec![0, 0, 2],
vec![0, 2, 0],
vec![0, 0, 4],
vec![0, 2, 0],
],
"ACAC",
"CA",
2, -2, -3,
"CA\nCA",
),
}
#[test]
fn test_score_function_match() {
assert_eq!(score_function('A', 'A', 1, -1, -2), 1);
assert_eq!(score_function('G', 'G', 2, -1, -1), 2);
}
#[test]
fn test_score_function_mismatch() {
assert_eq!(score_function('A', 'C', 1, -1, -2), -1);
assert_eq!(score_function('G', 'T', 1, -2, -1), -2);
}
#[test]
fn test_score_function_gap() {
assert_eq!(score_function('-', 'A', 1, -1, -2), -2);
assert_eq!(score_function('A', '-', 1, -1, -2), -2);
}
#[test]
fn test_case_insensitive() {
let result1 = smith_waterman("acac", "CA", 1, -1, -2);
let result2 = smith_waterman("ACAC", "ca", 1, -1, -2);
let result3 = smith_waterman("AcAc", "Ca", 1, -1, -2);
assert_eq!(result1, result2);
assert_eq!(result2, result3);
}
#[test]
fn test_custom_scoring_end_to_end() {
// Test with custom scoring parameters (match=2, mismatch=-2, gap=-3)
let query = "ACGT";
let subject = "ACGT";
let match_score = 2;
let mismatch_score = -2;
let gap_score = -3;
// Generate score matrix with custom parameters
let score_matrix = smith_waterman(query, subject, match_score, mismatch_score, gap_score);
// Traceback using the same custom parameters
let alignment = traceback(
&score_matrix,
query,
subject,
match_score,
mismatch_score,
gap_score,
);
// With perfect match and match_score=2, we expect alignment "ACGT\nACGT"
assert_eq!(alignment, "ACGT\nACGT");
// Verify the score is correct (4 matches × 2 = 8)
assert_eq!(score_matrix[4][4], 8);
}
#[test]
fn test_alignment_at_boundary() {
// Test case where optimal alignment might be at row/column 0
let query = "A";
let subject = "A";
let score_matrix = smith_waterman(query, subject, 1, -1, -2);
let alignment = traceback(&score_matrix, query, subject, 1, -1, -2);
// Should find the alignment even though it's near the boundary
assert_eq!(alignment, "A\nA");
assert_eq!(score_matrix[1][1], 1);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/fractional_knapsack.rs | src/dynamic_programming/fractional_knapsack.rs | pub fn fractional_knapsack(mut capacity: f64, weights: Vec<f64>, values: Vec<f64>) -> f64 {
// vector of tuple of weights and their value/weight ratio
let mut weights: Vec<(f64, f64)> = weights
.iter()
.zip(values.iter())
.map(|(&w, &v)| (w, v / w))
.collect();
// sort in decreasing order by value/weight ratio
weights.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).expect("Encountered NaN"));
dbg!(&weights);
// value to compute
let mut knapsack_value: f64 = 0.0;
// iterate through our vector.
for w in weights {
// w.0 is weight and w.1 value/weight ratio
if w.0 < capacity {
capacity -= w.0; // our sack is filling
knapsack_value += w.0 * w.1;
dbg!(&w.0, &knapsack_value);
} else {
// Multiply with capacity and not w.0
dbg!(&w.0, &knapsack_value);
knapsack_value += capacity * w.1;
break;
}
}
knapsack_value
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let capacity = 50.0;
let values = vec![60.0, 100.0, 120.0];
let weights = vec![10.0, 20.0, 30.0];
assert_eq!(fractional_knapsack(capacity, weights, values), 240.0);
}
#[test]
fn test2() {
let capacity = 60.0;
let values = vec![280.0, 100.0, 120.0, 120.0];
let weights = vec![40.0, 10.0, 20.0, 24.0];
assert_eq!(fractional_knapsack(capacity, weights, values), 440.0);
}
#[test]
fn test3() {
let capacity = 50.0;
let values = vec![60.0, 100.0, 120.0];
let weights = vec![20.0, 50.0, 30.0];
assert_eq!(fractional_knapsack(capacity, weights, values), 180.0);
}
#[test]
fn test4() {
let capacity = 60.0;
let values = vec![30.0, 40.0, 45.0, 77.0, 90.0];
let weights = vec![5.0, 10.0, 15.0, 22.0, 25.0];
assert_eq!(fractional_knapsack(capacity, weights, values), 230.0);
}
#[test]
fn test5() {
let capacity = 10.0;
let values = vec![500.0];
let weights = vec![30.0];
assert_eq!(
format!("{:.2}", fractional_knapsack(capacity, weights, values)),
String::from("166.67")
);
}
#[test]
fn test6() {
let capacity = 36.0;
let values = vec![25.0, 25.0, 25.0, 6.0, 2.0];
let weights = vec![10.0, 10.0, 10.0, 4.0, 2.0];
assert_eq!(fractional_knapsack(capacity, weights, values), 83.0);
}
#[test]
#[should_panic]
fn test_nan() {
let capacity = 36.0;
// 2nd element is NaN
let values = vec![25.0, f64::NAN, 25.0, 6.0, 2.0];
let weights = vec![10.0, 10.0, 10.0, 4.0, 2.0];
assert_eq!(fractional_knapsack(capacity, weights, values), 83.0);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/task_assignment.rs | src/dynamic_programming/task_assignment.rs | // Task Assignment Problem using Bitmasking and DP in Rust
// Time Complexity: O(2^M * N) where M is number of people and N is number of tasks
// Space Complexity: O(2^M * N) for the DP table
use std::collections::HashMap;
/// Solves the task assignment problem where each person can do only certain tasks,
/// each person can do only one task, and each task is performed by only one person.
/// Uses bitmasking and dynamic programming to count total number of valid assignments.
///
/// # Arguments
/// * `task_performed` - A vector of vectors where each inner vector contains tasks
/// that a person can perform (1-indexed task numbers)
/// * `total_tasks` - The total number of tasks (N)
///
/// # Returns
/// * The total number of valid task assignments
pub fn count_task_assignments(task_performed: Vec<Vec<usize>>, total_tasks: usize) -> i64 {
let num_people = task_performed.len();
let dp_size = 1 << num_people;
// Initialize DP table with -1 (uncomputed)
let mut dp = vec![vec![-1; total_tasks + 2]; dp_size];
let mut task_map = HashMap::new();
let final_mask = (1 << num_people) - 1;
// Build the task -> people mapping
for (person, tasks) in task_performed.iter().enumerate() {
for &task in tasks {
task_map.entry(task).or_insert_with(Vec::new).push(person);
}
}
// Recursive DP function
fn count_ways_until(
dp: &mut Vec<Vec<i64>>,
task_map: &HashMap<usize, Vec<usize>>,
final_mask: usize,
total_tasks: usize,
mask: usize,
task_no: usize,
) -> i64 {
// Base case: all people have been assigned tasks
if mask == final_mask {
return 1;
}
// Base case: no more tasks available but not all people assigned
if task_no > total_tasks {
return 0;
}
// Return cached result if already computed
if dp[mask][task_no] != -1 {
return dp[mask][task_no];
}
// Option 1: Skip the current task
let mut total_ways =
count_ways_until(dp, task_map, final_mask, total_tasks, mask, task_no + 1);
// Option 2: Assign current task to a capable person who isn't busy
if let Some(people) = task_map.get(&task_no) {
for &person in people {
// Check if this person is already assigned a task
if mask & (1 << person) != 0 {
continue;
}
// Assign task to this person and recurse
total_ways += count_ways_until(
dp,
task_map,
final_mask,
total_tasks,
mask | (1 << person),
task_no + 1,
);
}
}
// Cache the result
dp[mask][task_no] = total_ways;
total_ways
}
// Start recursion with no people assigned and first task
count_ways_until(&mut dp, &task_map, final_mask, total_tasks, 0, 1)
}
#[cfg(test)]
mod tests {
use super::*;
// Macro to generate multiple test cases for the task assignment function
macro_rules! task_assignment_tests {
($($name:ident: $input:expr => $expected:expr,)*) => {
$(
#[test]
fn $name() {
let (task_performed, total_tasks) = $input;
assert_eq!(count_task_assignments(task_performed, total_tasks), $expected);
}
)*
};
}
task_assignment_tests! {
test_case_1: (vec![vec![1, 3, 4], vec![1, 2, 5], vec![3, 4]], 5) => 10,
test_case_2: (vec![vec![1, 2], vec![1, 2]], 2) => 2,
test_case_3: (vec![vec![1], vec![2], vec![3]], 3) => 1,
test_case_4: (vec![vec![1, 2, 3], vec![1, 2, 3], vec![1, 2, 3]], 3) => 6,
test_case_5: (vec![vec![1], vec![1]], 1) => 0,
// Edge test case
test_case_single_person: (vec![vec![1, 2, 3]], 3) => 3,
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/integer_partition.rs | src/dynamic_programming/integer_partition.rs | //! Integer partition using dynamic programming
//!
//! The number of partitions of a number n into at least k parts equals the number of
//! partitions into exactly k parts plus the number of partitions into at least k-1 parts.
//! Subtracting 1 from each part of a partition of n into k parts gives a partition of n-k
//! into k parts. These two facts together are used for this algorithm.
//!
//! More info:
//! * <https://en.wikipedia.org/wiki/Partition_(number_theory)>
//! * <https://en.wikipedia.org/wiki/Partition_function_(number_theory)>
#![allow(clippy::large_stack_arrays)]
/// Calculates the number of partitions of a positive integer using dynamic programming.
///
/// # Arguments
///
/// * `m` - A positive integer to find the number of partitions for
///
/// # Returns
///
/// The number of partitions of `m`
///
/// # Panics
///
/// Panics if `m` is not a positive integer (0 or negative)
///
/// # Examples
///
/// ```
/// # use the_algorithms_rust::dynamic_programming::partition;
/// assert_eq!(partition(5), 7);
/// assert_eq!(partition(7), 15);
/// assert_eq!(partition(100), 190569292);
/// ```
#[allow(clippy::large_stack_arrays)]
pub fn partition(m: i32) -> u128 {
// Validate input
assert!(m > 0, "Input must be a positive integer greater than 0");
let m = m as usize;
// Initialize memo table with zeros using iterative construction
// to avoid large stack allocations
let mut memo: Vec<Vec<u128>> = Vec::with_capacity(m + 1);
for _ in 0..=m {
memo.push(vec![0u128; m]);
}
// Base case: there's one way to partition into 0 parts (empty partition)
for i in 0..=m {
memo[i][0] = 1;
}
// Fill the memo table using dynamic programming
for n in 0..=m {
for k in 1..m {
// Add partitions from k-1 (partitions with at least k-1 parts)
memo[n][k] += memo[n][k - 1];
// Add partitions from n-k-1 with k parts (subtract 1 from each part)
if n > k {
memo[n][k] += memo[n - k - 1][k];
}
}
}
memo[m][m - 1]
}
#[cfg(test)]
#[allow(clippy::large_stack_arrays)]
mod tests {
use super::*;
#[test]
fn test_partition_5() {
assert_eq!(partition(5), 7);
}
#[test]
fn test_partition_7() {
assert_eq!(partition(7), 15);
}
#[test]
#[allow(clippy::large_stack_arrays)]
fn test_partition_100() {
assert_eq!(partition(100), 190569292);
}
#[test]
#[allow(clippy::large_stack_arrays)]
fn test_partition_1000() {
assert_eq!(partition(1000), 24061467864032622473692149727991);
}
#[test]
#[should_panic(expected = "Input must be a positive integer greater than 0")]
fn test_partition_negative() {
partition(-7);
}
#[test]
#[should_panic(expected = "Input must be a positive integer greater than 0")]
fn test_partition_zero() {
partition(0);
}
#[test]
fn test_partition_small_values() {
assert_eq!(partition(1), 1);
assert_eq!(partition(2), 2);
assert_eq!(partition(3), 3);
assert_eq!(partition(4), 5);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/snail.rs | src/dynamic_programming/snail.rs | /// ## Spiral Sorting
///
/// Given an n x m array, return the array elements arranged from outermost elements
/// to the middle element, traveling INWARD FROM TOP-LEFT, CLOCKWISE.
pub fn snail<T: Copy>(matrix: &[Vec<T>]) -> Vec<T> {
// break on empty matrix
if matrix.is_empty() || matrix[0].is_empty() {
return vec![];
}
let col_count = matrix[0].len();
let row_count = matrix.len();
// Initial maximum/minimum indices
let mut max_col = col_count - 1;
let mut min_col = 0;
let mut max_row = row_count - 1;
let mut min_row = 0;
// Initial direction is Right because
// we start from the top-left corner of the matrix at indices [0][0]
let mut dir = Direction::Right;
let mut row = 0;
let mut col = 0;
let mut result = Vec::new();
while result.len() < row_count * col_count {
result.push(matrix[row][col]);
dir.snail_move(
&mut col,
&mut row,
&mut min_col,
&mut max_col,
&mut min_row,
&mut max_row,
);
}
result
}
enum Direction {
Right,
Left,
Down,
Up,
}
impl Direction {
pub fn snail_move(
&mut self,
col: &mut usize,
row: &mut usize,
min_col: &mut usize,
max_col: &mut usize,
min_row: &mut usize,
max_row: &mut usize,
) {
match self {
Self::Right => {
*col = if *col < *max_col {
*col + 1
} else {
*self = Self::Down;
*min_row += 1;
*row = *min_row;
*col
};
}
Self::Down => {
*row = if *row < *max_row {
*row + 1
} else {
*self = Self::Left;
*max_col -= 1;
*col = *max_col;
*row
};
}
Self::Left => {
*col = if *col > usize::MIN && *col > *min_col {
*col - 1
} else {
*self = Self::Up;
*max_row -= 1;
*row = *max_row;
*col
};
}
Self::Up => {
*row = if *row > usize::MIN && *row > *min_row {
*row - 1
} else {
*self = Self::Right;
*min_col += 1;
*col = *min_col;
*row
};
}
};
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_empty() {
let empty: &[Vec<i32>] = &[vec![]];
assert_eq!(snail(empty), vec![]);
}
#[test]
fn test_int() {
let square = &[vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
assert_eq!(snail(square), vec![1, 2, 3, 6, 9, 8, 7, 4, 5]);
}
#[test]
fn test_char() {
let square = &[
vec!['S', 'O', 'M'],
vec!['E', 'T', 'H'],
vec!['I', 'N', 'G'],
];
assert_eq!(
snail(square),
vec!['S', 'O', 'M', 'H', 'G', 'N', 'I', 'E', 'T']
);
}
#[test]
fn test_rect() {
let square = &[
vec!['H', 'E', 'L', 'L'],
vec!['O', ' ', 'W', 'O'],
vec!['R', 'L', 'D', ' '],
];
assert_eq!(
snail(square),
vec!['H', 'E', 'L', 'L', 'O', ' ', 'D', 'L', 'R', 'O', ' ', 'W']
);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/catalan_numbers.rs | src/dynamic_programming/catalan_numbers.rs | //! Catalan Numbers using Dynamic Programming
//!
//! The Catalan numbers are a sequence of positive integers that appear in many
//! counting problems in combinatorics. Such problems include counting:
//! - The number of Dyck words of length 2n
//! - The number of well-formed expressions with n pairs of parentheses
//! (e.g., `()()` is valid but `())(` is not)
//! - The number of different ways n + 1 factors can be completely parenthesized
//! (e.g., for n = 2, C(n) = 2 and (ab)c and a(bc) are the two valid ways)
//! - The number of full binary trees with n + 1 leaves
//!
//! A Catalan number satisfies the following recurrence relation:
//! - C(0) = C(1) = 1
//! - C(n) = sum(C(i) * C(n-i-1)), from i = 0 to n-1
//!
//! Sources:
//! - [Brilliant.org](https://brilliant.org/wiki/catalan-numbers/)
//! - [Wikipedia](https://en.wikipedia.org/wiki/Catalan_number)
/// Computes the Catalan number sequence from 0 through `upper_limit`.
///
/// # Arguments
///
/// * `upper_limit` - The upper limit for the Catalan sequence (must be ≥ 0)
///
/// # Returns
///
/// A vector containing Catalan numbers from C(0) to C(upper_limit)
///
/// # Complexity
///
/// * Time complexity: O(n²)
/// * Space complexity: O(n)
///
/// where `n` is the `upper_limit`.
///
/// # Examples
///
/// ```
/// use the_algorithms_rust::dynamic_programming::catalan_numbers;
///
/// assert_eq!(catalan_numbers(5), vec![1, 1, 2, 5, 14, 42]);
/// assert_eq!(catalan_numbers(2), vec![1, 1, 2]);
/// assert_eq!(catalan_numbers(0), vec![1]);
/// ```
///
/// # Warning
///
/// This will overflow the 64-bit unsigned integer for large values of `upper_limit`.
/// For example, C(21) and beyond will cause overflow.
pub fn catalan_numbers(upper_limit: usize) -> Vec<u64> {
let mut catalan_list = vec![0u64; upper_limit + 1];
// Base case: C(0) = 1
catalan_list[0] = 1;
// Base case: C(1) = 1
if upper_limit > 0 {
catalan_list[1] = 1;
}
// Recurrence relation: C(i) = sum(C(j) * C(i-j-1)), from j = 0 to i-1
for i in 2..=upper_limit {
for j in 0..i {
catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1];
}
}
catalan_list
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_catalan_numbers_basic() {
assert_eq!(catalan_numbers(5), vec![1, 1, 2, 5, 14, 42]);
assert_eq!(catalan_numbers(2), vec![1, 1, 2]);
assert_eq!(catalan_numbers(0), vec![1]);
}
#[test]
fn test_catalan_numbers_single() {
assert_eq!(catalan_numbers(1), vec![1, 1]);
}
#[test]
fn test_catalan_numbers_extended() {
let result = catalan_numbers(10);
assert_eq!(result.len(), 11);
assert_eq!(result[0], 1);
assert_eq!(result[1], 1);
assert_eq!(result[2], 2);
assert_eq!(result[3], 5);
assert_eq!(result[4], 14);
assert_eq!(result[5], 42);
assert_eq!(result[6], 132);
assert_eq!(result[7], 429);
assert_eq!(result[8], 1430);
assert_eq!(result[9], 4862);
assert_eq!(result[10], 16796);
}
#[test]
fn test_catalan_first_few() {
// Verify the first few Catalan numbers match known values
assert_eq!(catalan_numbers(3), vec![1, 1, 2, 5]);
assert_eq!(catalan_numbers(4), vec![1, 1, 2, 5, 14]);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/optimal_bst.rs | src/dynamic_programming/optimal_bst.rs | // Optimal Binary Search Tree Algorithm in Rust
// Time Complexity: O(n^3) with prefix sum optimization
// Space Complexity: O(n^2) for the dp table and prefix sum array
/// Constructs an Optimal Binary Search Tree from a list of key frequencies.
/// The goal is to minimize the expected search cost given key access frequencies.
///
/// # Arguments
/// * `freq` - A slice of integers representing the frequency of key access
///
/// # Returns
/// * An integer representing the minimum cost of the optimal BST
pub fn optimal_search_tree(freq: &[i32]) -> i32 {
let n = freq.len();
if n == 0 {
return 0;
}
// dp[i][j] stores the cost of optimal BST that can be formed from keys[i..=j]
let mut dp = vec![vec![0; n]; n];
// prefix_sum[i] stores sum of freq[0..i]
let mut prefix_sum = vec![0; n + 1];
for i in 0..n {
prefix_sum[i + 1] = prefix_sum[i] + freq[i];
}
// Base case: Trees with only one key
for i in 0..n {
dp[i][i] = freq[i];
}
// Build chains of increasing length l (from 2 to n)
for l in 2..=n {
for i in 0..=n - l {
let j = i + l - 1;
dp[i][j] = i32::MAX;
// Compute the total frequency sum in the range [i..=j] using prefix sum
let fsum = prefix_sum[j + 1] - prefix_sum[i];
// Try making each key in freq[i..=j] the root of the tree
for r in i..=j {
// Cost of left subtree
let left = if r > i { dp[i][r - 1] } else { 0 };
// Cost of right subtree
let right = if r < j { dp[r + 1][j] } else { 0 };
// Total cost = left + right + sum of frequencies (fsum)
let cost = left + right + fsum;
// Choose the minimum among all possible roots
if cost < dp[i][j] {
dp[i][j] = cost;
}
}
}
}
// Minimum cost of the optimal BST storing all keys
dp[0][n - 1]
}
#[cfg(test)]
mod tests {
use super::*;
// Macro to generate multiple test cases for the optimal_search_tree function
macro_rules! optimal_bst_tests {
($($name:ident: $input:expr => $expected:expr,)*) => {
$(
#[test]
fn $name() {
let freq = $input;
assert_eq!(optimal_search_tree(freq), $expected);
}
)*
};
}
optimal_bst_tests! {
// Common test cases
test_case_1: &[34, 10, 8, 50] => 180,
test_case_2: &[10, 12] => 32,
test_case_3: &[10, 12, 20] => 72,
test_case_4: &[25, 10, 20] => 95,
test_case_5: &[4, 2, 6, 3] => 26,
// Edge test cases
test_case_single: &[42] => 42,
test_case_empty: &[] => 0,
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/mod.rs | src/dynamic_programming/mod.rs | mod catalan_numbers;
mod coin_change;
mod egg_dropping;
mod fibonacci;
mod fractional_knapsack;
mod integer_partition;
mod is_subsequence;
mod knapsack;
mod longest_common_subsequence;
mod longest_common_substring;
mod longest_continuous_increasing_subsequence;
mod longest_increasing_subsequence;
mod matrix_chain_multiply;
mod maximal_square;
mod maximum_subarray;
mod minimum_cost_path;
mod optimal_bst;
mod palindrome_partitioning;
mod rod_cutting;
mod smith_waterman;
mod snail;
mod subset_generation;
mod subset_sum;
mod task_assignment;
mod trapped_rainwater;
mod word_break;
pub use self::catalan_numbers::catalan_numbers;
pub use self::coin_change::coin_change;
pub use self::egg_dropping::egg_drop;
pub use self::fibonacci::{
binary_lifting_fibonacci, classical_fibonacci, fibonacci,
last_digit_of_the_sum_of_nth_fibonacci_number, logarithmic_fibonacci, matrix_fibonacci,
memoized_fibonacci, nth_fibonacci_number_modulo_m, recursive_fibonacci,
};
pub use self::fractional_knapsack::fractional_knapsack;
pub use self::integer_partition::partition;
pub use self::is_subsequence::is_subsequence;
pub use self::knapsack::knapsack;
pub use self::longest_common_subsequence::longest_common_subsequence;
pub use self::longest_common_substring::longest_common_substring;
pub use self::longest_continuous_increasing_subsequence::longest_continuous_increasing_subsequence;
pub use self::longest_increasing_subsequence::longest_increasing_subsequence;
pub use self::matrix_chain_multiply::matrix_chain_multiply;
pub use self::maximal_square::maximal_square;
pub use self::maximum_subarray::maximum_subarray;
pub use self::minimum_cost_path::minimum_cost_path;
pub use self::optimal_bst::optimal_search_tree;
pub use self::palindrome_partitioning::minimum_palindrome_partitions;
pub use self::rod_cutting::rod_cut;
pub use self::smith_waterman::{score_function, smith_waterman, traceback};
pub use self::snail::snail;
pub use self::subset_generation::list_subset;
pub use self::subset_sum::is_sum_subset;
pub use self::task_assignment::count_task_assignments;
pub use self::trapped_rainwater::trapped_rainwater;
pub use self::word_break::word_break;
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/egg_dropping.rs | src/dynamic_programming/egg_dropping.rs | //! This module contains the `egg_drop` function, which determines the minimum number of egg droppings
//! required to find the highest floor from which an egg can be dropped without breaking. It also includes
//! tests for the function using various test cases, including edge cases.
/// Returns the least number of egg droppings required to determine the highest floor from which an egg will not break upon dropping.
///
/// # Arguments
///
/// * `eggs` - The number of eggs available.
/// * `floors` - The number of floors in the building.
///
/// # Returns
///
/// * `Some(usize)` - The minimum number of drops required if the number of eggs is greater than 0.
/// * `None` - If the number of eggs is 0.
pub fn egg_drop(eggs: usize, floors: usize) -> Option<usize> {
if eggs == 0 {
return None;
}
if eggs == 1 || floors == 0 || floors == 1 {
return Some(floors);
}
// Create a 2D vector to store solutions to subproblems
let mut egg_drops: Vec<Vec<usize>> = vec![vec![0; floors + 1]; eggs + 1];
// Base cases: 0 floors -> 0 drops, 1 floor -> 1 drop
(1..=eggs).for_each(|i| {
egg_drops[i][1] = 1;
});
// Base case: 1 egg -> k drops for k floors
(1..=floors).for_each(|j| {
egg_drops[1][j] = j;
});
// Fill the table using the optimal substructure property
(2..=eggs).for_each(|i| {
(2..=floors).for_each(|j| {
egg_drops[i][j] = (1..=j)
.map(|k| 1 + std::cmp::max(egg_drops[i - 1][k - 1], egg_drops[i][j - k]))
.min()
.unwrap();
});
});
Some(egg_drops[eggs][floors])
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! egg_drop_tests {
($($name:ident: $test_cases:expr,)*) => {
$(
#[test]
fn $name() {
let (eggs, floors, expected) = $test_cases;
assert_eq!(egg_drop(eggs, floors), expected);
}
)*
}
}
egg_drop_tests! {
test_no_floors: (5, 0, Some(0)),
test_one_egg_multiple_floors: (1, 8, Some(8)),
test_multiple_eggs_one_floor: (5, 1, Some(1)),
test_two_eggs_two_floors: (2, 2, Some(2)),
test_three_eggs_five_floors: (3, 5, Some(3)),
test_two_eggs_ten_floors: (2, 10, Some(4)),
test_two_eggs_thirty_six_floors: (2, 36, Some(8)),
test_many_eggs_one_floor: (100, 1, Some(1)),
test_many_eggs_few_floors: (100, 5, Some(3)),
test_few_eggs_many_floors: (2, 1000, Some(45)),
test_zero_eggs: (0, 10, None::<usize>),
test_no_eggs_no_floors: (0, 0, None::<usize>),
test_one_egg_no_floors: (1, 0, Some(0)),
test_one_egg_one_floor: (1, 1, Some(1)),
test_maximum_floors_one_egg: (1, usize::MAX, Some(usize::MAX)),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/fibonacci.rs | src/dynamic_programming/fibonacci.rs | /// Fibonacci via Dynamic Programming
use std::collections::HashMap;
/// fibonacci(n) returns the nth fibonacci number
/// This function uses the definition of Fibonacci where:
/// F(0) = F(1) = 1 and F(n+1) = F(n) + F(n-1) for n>0
///
/// Warning: This will overflow the 128-bit unsigned integer at n=186
pub fn fibonacci(n: u32) -> u128 {
// Use a and b to store the previous two values in the sequence
let mut a = 0;
let mut b = 1;
for _i in 0..n {
// As we iterate through, move b's value into a and the new computed
// value into b.
let c = a + b;
a = b;
b = c;
}
b
}
/// fibonacci(n) returns the nth fibonacci number
/// This function uses the definition of Fibonacci where:
/// F(0) = F(1) = 1 and F(n+1) = F(n) + F(n-1) for n>0
///
/// Warning: This will overflow the 128-bit unsigned integer at n=186
pub fn recursive_fibonacci(n: u32) -> u128 {
// Call the actual tail recursive implementation, with the extra
// arguments set up.
_recursive_fibonacci(n, 0, 1)
}
fn _recursive_fibonacci(n: u32, previous: u128, current: u128) -> u128 {
if n == 0 {
current
} else {
_recursive_fibonacci(n - 1, current, current + previous)
}
}
/// classical_fibonacci(n) returns the nth fibonacci number
/// This function uses the definition of Fibonacci where:
/// F(0) = 0, F(1) = 1 and F(n+1) = F(n) + F(n-1) for n>0
///
/// Warning: This will overflow the 128-bit unsigned integer at n=186
pub fn classical_fibonacci(n: u32) -> u128 {
match n {
0 => 0,
1 => 1,
_ => {
let k = n / 2;
let f1 = classical_fibonacci(k);
let f2 = classical_fibonacci(k - 1);
match n % 4 {
0 | 2 => f1 * (f1 + 2 * f2),
1 => (2 * f1 + f2) * (2 * f1 - f2) + 2,
_ => (2 * f1 + f2) * (2 * f1 - f2) - 2,
}
}
}
}
/// logarithmic_fibonacci(n) returns the nth fibonacci number
/// This function uses the definition of Fibonacci where:
/// F(0) = 0, F(1) = 1 and F(n+1) = F(n) + F(n-1) for n>0
///
/// Warning: This will overflow the 128-bit unsigned integer at n=186
pub fn logarithmic_fibonacci(n: u32) -> u128 {
// if it is the max value before overflow, use n-1 then get the second
// value in the tuple
if n == 186 {
let (_, second) = _logarithmic_fibonacci(185);
second
} else {
let (first, _) = _logarithmic_fibonacci(n);
first
}
}
fn _logarithmic_fibonacci(n: u32) -> (u128, u128) {
match n {
0 => (0, 1),
_ => {
let (current, next) = _logarithmic_fibonacci(n / 2);
let c = current * (next * 2 - current);
let d = current * current + next * next;
match n % 2 {
0 => (c, d),
_ => (d, c + d),
}
}
}
}
/// Memoized fibonacci.
pub fn memoized_fibonacci(n: u32) -> u128 {
let mut cache: HashMap<u32, u128> = HashMap::new();
_memoized_fibonacci(n, &mut cache)
}
fn _memoized_fibonacci(n: u32, cache: &mut HashMap<u32, u128>) -> u128 {
if n == 0 {
return 0;
}
if n == 1 {
return 1;
}
let f = match cache.get(&n) {
Some(f) => f,
None => {
let f1 = _memoized_fibonacci(n - 1, cache);
let f2 = _memoized_fibonacci(n - 2, cache);
cache.insert(n, f1 + f2);
cache.get(&n).unwrap()
}
};
*f
}
/// matrix_fibonacci(n) returns the nth fibonacci number
/// This function uses the definition of Fibonacci where:
/// F(0) = 0, F(1) = 1 and F(n+1) = F(n) + F(n-1) for n>0
///
/// Matrix formula:
/// [F(n + 2)] = [1, 1] * [F(n + 1)]
/// [F(n + 1)] [1, 0] [F(n) ]
///
/// Warning: This will overflow the 128-bit unsigned integer at n=186
pub fn matrix_fibonacci(n: u32) -> u128 {
let multiplier: Vec<Vec<u128>> = vec![vec![1, 1], vec![1, 0]];
let multiplier = matrix_power(&multiplier, n);
let initial_fib_matrix: Vec<Vec<u128>> = vec![vec![1], vec![0]];
let res = matrix_multiply(&multiplier, &initial_fib_matrix);
res[1][0]
}
fn matrix_power(base: &Vec<Vec<u128>>, power: u32) -> Vec<Vec<u128>> {
let identity_matrix: Vec<Vec<u128>> = vec![vec![1, 0], vec![0, 1]];
vec![base; power as usize]
.iter()
.fold(identity_matrix, |acc, x| matrix_multiply(&acc, x))
}
// Copied from matrix_ops since u128 is required instead of i32
#[allow(clippy::needless_range_loop)]
fn matrix_multiply(multiplier: &[Vec<u128>], multiplicand: &[Vec<u128>]) -> Vec<Vec<u128>> {
// Multiply two matching matrices. The multiplier needs to have the same amount
// of columns as the multiplicand has rows.
let mut result: Vec<Vec<u128>> = vec![];
let mut temp;
// Using variable to compare lengths of rows in multiplicand later
let row_right_length = multiplicand[0].len();
for row_left in 0..multiplier.len() {
if multiplier[row_left].len() != multiplicand.len() {
panic!("Matrix dimensions do not match");
}
result.push(vec![]);
for column_right in 0..multiplicand[0].len() {
temp = 0;
for row_right in 0..multiplicand.len() {
if row_right_length != multiplicand[row_right].len() {
// If row is longer than a previous row cancel operation with error
panic!("Matrix dimensions do not match");
}
temp += multiplier[row_left][row_right] * multiplicand[row_right][column_right];
}
result[row_left].push(temp);
}
}
result
}
/// Binary lifting fibonacci
///
/// Following properties of F(n) could be deduced from the matrix formula above:
///
/// F(2n) = F(n) * (2F(n+1) - F(n))
/// F(2n+1) = F(n+1)^2 + F(n)^2
///
/// Therefore F(n) and F(n+1) can be derived from F(n>>1) and F(n>>1 + 1), which
/// has a smaller constant in both time and space compared to matrix fibonacci.
pub fn binary_lifting_fibonacci(n: u32) -> u128 {
// the state always stores F(k), F(k+1) for some k, initially F(0), F(1)
let mut state = (0u128, 1u128);
for i in (0..u32::BITS - n.leading_zeros()).rev() {
// compute F(2k), F(2k+1) from F(k), F(k+1)
state = (
state.0 * (2 * state.1 - state.0),
state.0 * state.0 + state.1 * state.1,
);
if n & (1 << i) != 0 {
state = (state.1, state.0 + state.1);
}
}
state.0
}
/// nth_fibonacci_number_modulo_m(n, m) returns the nth fibonacci number modulo the specified m
/// i.e. F(n) % m
pub fn nth_fibonacci_number_modulo_m(n: i64, m: i64) -> i128 {
let (length, pisano_sequence) = get_pisano_sequence_and_period(m);
let remainder = n % length as i64;
pisano_sequence[remainder as usize].to_owned()
}
/// get_pisano_sequence_and_period(m) returns the Pisano Sequence and period for the specified integer m.
/// The pisano period is the period with which the sequence of Fibonacci numbers taken modulo m repeats.
/// The pisano sequence is the numbers in pisano period.
fn get_pisano_sequence_and_period(m: i64) -> (i128, Vec<i128>) {
let mut a = 0;
let mut b = 1;
let mut length: i128 = 0;
let mut pisano_sequence: Vec<i128> = vec![a, b];
// Iterating through all the fib numbers to get the sequence
for _i in 0..=(m * m) {
let c = (a + b) % m as i128;
// adding number into the sequence
pisano_sequence.push(c);
a = b;
b = c;
if a == 0 && b == 1 {
// Remove the last two elements from the sequence
// This is a less elegant way to do it.
pisano_sequence.pop();
pisano_sequence.pop();
length = pisano_sequence.len() as i128;
break;
}
}
(length, pisano_sequence)
}
/// last_digit_of_the_sum_of_nth_fibonacci_number(n) returns the last digit of the sum of n fibonacci numbers.
/// The function uses the definition of Fibonacci where:
/// F(0) = 0, F(1) = 1 and F(n+1) = F(n) + F(n-1) for n > 2
///
/// The sum of the Fibonacci numbers are:
/// F(0) + F(1) + F(2) + ... + F(n)
pub fn last_digit_of_the_sum_of_nth_fibonacci_number(n: i64) -> i64 {
if n < 2 {
return n;
}
// the pisano period of mod 10 is 60
let n = ((n + 2) % 60) as usize;
let mut fib = vec![0; n + 1];
fib[0] = 0;
fib[1] = 1;
for i in 2..=n {
fib[i] = (fib[i - 1] % 10 + fib[i - 2] % 10) % 10;
}
if fib[n] == 0 {
return 9;
}
fib[n] % 10 - 1
}
#[cfg(test)]
mod tests {
use super::binary_lifting_fibonacci;
use super::classical_fibonacci;
use super::fibonacci;
use super::last_digit_of_the_sum_of_nth_fibonacci_number;
use super::logarithmic_fibonacci;
use super::matrix_fibonacci;
use super::memoized_fibonacci;
use super::nth_fibonacci_number_modulo_m;
use super::recursive_fibonacci;
#[test]
fn test_fibonacci() {
assert_eq!(fibonacci(0), 1);
assert_eq!(fibonacci(1), 1);
assert_eq!(fibonacci(2), 2);
assert_eq!(fibonacci(3), 3);
assert_eq!(fibonacci(4), 5);
assert_eq!(fibonacci(5), 8);
assert_eq!(fibonacci(10), 89);
assert_eq!(fibonacci(20), 10946);
assert_eq!(fibonacci(100), 573147844013817084101);
assert_eq!(fibonacci(184), 205697230343233228174223751303346572685);
}
#[test]
fn test_recursive_fibonacci() {
assert_eq!(recursive_fibonacci(0), 1);
assert_eq!(recursive_fibonacci(1), 1);
assert_eq!(recursive_fibonacci(2), 2);
assert_eq!(recursive_fibonacci(3), 3);
assert_eq!(recursive_fibonacci(4), 5);
assert_eq!(recursive_fibonacci(5), 8);
assert_eq!(recursive_fibonacci(10), 89);
assert_eq!(recursive_fibonacci(20), 10946);
assert_eq!(recursive_fibonacci(100), 573147844013817084101);
assert_eq!(
recursive_fibonacci(184),
205697230343233228174223751303346572685
);
}
#[test]
fn test_classical_fibonacci() {
assert_eq!(classical_fibonacci(0), 0);
assert_eq!(classical_fibonacci(1), 1);
assert_eq!(classical_fibonacci(2), 1);
assert_eq!(classical_fibonacci(3), 2);
assert_eq!(classical_fibonacci(4), 3);
assert_eq!(classical_fibonacci(5), 5);
assert_eq!(classical_fibonacci(10), 55);
assert_eq!(classical_fibonacci(20), 6765);
assert_eq!(classical_fibonacci(21), 10946);
assert_eq!(classical_fibonacci(100), 354224848179261915075);
assert_eq!(
classical_fibonacci(184),
127127879743834334146972278486287885163
);
}
#[test]
fn test_logarithmic_fibonacci() {
assert_eq!(logarithmic_fibonacci(0), 0);
assert_eq!(logarithmic_fibonacci(1), 1);
assert_eq!(logarithmic_fibonacci(2), 1);
assert_eq!(logarithmic_fibonacci(3), 2);
assert_eq!(logarithmic_fibonacci(4), 3);
assert_eq!(logarithmic_fibonacci(5), 5);
assert_eq!(logarithmic_fibonacci(10), 55);
assert_eq!(logarithmic_fibonacci(20), 6765);
assert_eq!(logarithmic_fibonacci(21), 10946);
assert_eq!(logarithmic_fibonacci(100), 354224848179261915075);
assert_eq!(
logarithmic_fibonacci(184),
127127879743834334146972278486287885163
);
}
#[test]
/// Check that the iterative and recursive fibonacci
/// produce the same value. Both are combinatorial ( F(0) = F(1) = 1 )
fn test_iterative_and_recursive_equivalence() {
assert_eq!(fibonacci(0), recursive_fibonacci(0));
assert_eq!(fibonacci(1), recursive_fibonacci(1));
assert_eq!(fibonacci(2), recursive_fibonacci(2));
assert_eq!(fibonacci(3), recursive_fibonacci(3));
assert_eq!(fibonacci(4), recursive_fibonacci(4));
assert_eq!(fibonacci(5), recursive_fibonacci(5));
assert_eq!(fibonacci(10), recursive_fibonacci(10));
assert_eq!(fibonacci(20), recursive_fibonacci(20));
assert_eq!(fibonacci(100), recursive_fibonacci(100));
assert_eq!(fibonacci(184), recursive_fibonacci(184));
}
#[test]
/// Check that classical and combinatorial fibonacci produce the
/// same value when 'n' differs by 1.
/// classical fibonacci: ( F(0) = 0, F(1) = 1 )
/// combinatorial fibonacci: ( F(0) = F(1) = 1 )
fn test_classical_and_combinatorial_are_off_by_one() {
assert_eq!(classical_fibonacci(1), fibonacci(0));
assert_eq!(classical_fibonacci(2), fibonacci(1));
assert_eq!(classical_fibonacci(3), fibonacci(2));
assert_eq!(classical_fibonacci(4), fibonacci(3));
assert_eq!(classical_fibonacci(5), fibonacci(4));
assert_eq!(classical_fibonacci(6), fibonacci(5));
assert_eq!(classical_fibonacci(11), fibonacci(10));
assert_eq!(classical_fibonacci(20), fibonacci(19));
assert_eq!(classical_fibonacci(21), fibonacci(20));
assert_eq!(classical_fibonacci(101), fibonacci(100));
assert_eq!(classical_fibonacci(185), fibonacci(184));
}
#[test]
fn test_memoized_fibonacci() {
assert_eq!(memoized_fibonacci(0), 0);
assert_eq!(memoized_fibonacci(1), 1);
assert_eq!(memoized_fibonacci(2), 1);
assert_eq!(memoized_fibonacci(3), 2);
assert_eq!(memoized_fibonacci(4), 3);
assert_eq!(memoized_fibonacci(5), 5);
assert_eq!(memoized_fibonacci(10), 55);
assert_eq!(memoized_fibonacci(20), 6765);
assert_eq!(memoized_fibonacci(21), 10946);
assert_eq!(memoized_fibonacci(100), 354224848179261915075);
assert_eq!(
memoized_fibonacci(184),
127127879743834334146972278486287885163
);
}
#[test]
fn test_matrix_fibonacci() {
assert_eq!(matrix_fibonacci(0), 0);
assert_eq!(matrix_fibonacci(1), 1);
assert_eq!(matrix_fibonacci(2), 1);
assert_eq!(matrix_fibonacci(3), 2);
assert_eq!(matrix_fibonacci(4), 3);
assert_eq!(matrix_fibonacci(5), 5);
assert_eq!(matrix_fibonacci(10), 55);
assert_eq!(matrix_fibonacci(20), 6765);
assert_eq!(matrix_fibonacci(21), 10946);
assert_eq!(matrix_fibonacci(100), 354224848179261915075);
assert_eq!(
matrix_fibonacci(184),
127127879743834334146972278486287885163
);
}
#[test]
fn test_binary_lifting_fibonacci() {
assert_eq!(binary_lifting_fibonacci(0), 0);
assert_eq!(binary_lifting_fibonacci(1), 1);
assert_eq!(binary_lifting_fibonacci(2), 1);
assert_eq!(binary_lifting_fibonacci(3), 2);
assert_eq!(binary_lifting_fibonacci(4), 3);
assert_eq!(binary_lifting_fibonacci(5), 5);
assert_eq!(binary_lifting_fibonacci(10), 55);
assert_eq!(binary_lifting_fibonacci(20), 6765);
assert_eq!(binary_lifting_fibonacci(21), 10946);
assert_eq!(binary_lifting_fibonacci(100), 354224848179261915075);
assert_eq!(
binary_lifting_fibonacci(184),
127127879743834334146972278486287885163
);
}
#[test]
fn test_nth_fibonacci_number_modulo_m() {
assert_eq!(nth_fibonacci_number_modulo_m(5, 10), 5);
assert_eq!(nth_fibonacci_number_modulo_m(10, 7), 6);
assert_eq!(nth_fibonacci_number_modulo_m(20, 100), 65);
assert_eq!(nth_fibonacci_number_modulo_m(1, 5), 1);
assert_eq!(nth_fibonacci_number_modulo_m(0, 15), 0);
assert_eq!(nth_fibonacci_number_modulo_m(50, 1000), 25);
assert_eq!(nth_fibonacci_number_modulo_m(100, 37), 7);
assert_eq!(nth_fibonacci_number_modulo_m(15, 2), 0);
assert_eq!(nth_fibonacci_number_modulo_m(8, 1_000_000), 21);
assert_eq!(nth_fibonacci_number_modulo_m(1000, 997), 996);
assert_eq!(nth_fibonacci_number_modulo_m(200, 123), 0);
}
#[test]
fn test_last_digit_of_the_sum_of_nth_fibonacci_number() {
assert_eq!(last_digit_of_the_sum_of_nth_fibonacci_number(0), 0);
assert_eq!(last_digit_of_the_sum_of_nth_fibonacci_number(1), 1);
assert_eq!(last_digit_of_the_sum_of_nth_fibonacci_number(2), 2);
assert_eq!(last_digit_of_the_sum_of_nth_fibonacci_number(3), 4);
assert_eq!(last_digit_of_the_sum_of_nth_fibonacci_number(4), 7);
assert_eq!(last_digit_of_the_sum_of_nth_fibonacci_number(5), 2);
assert_eq!(last_digit_of_the_sum_of_nth_fibonacci_number(25), 7);
assert_eq!(last_digit_of_the_sum_of_nth_fibonacci_number(50), 8);
assert_eq!(last_digit_of_the_sum_of_nth_fibonacci_number(100), 5);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/maximal_square.rs | src/dynamic_programming/maximal_square.rs | use std::cmp::max;
use std::cmp::min;
/// Maximal Square
///
/// Given an `m` * `n` binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.\
/// <https://leetcode.com/problems/maximal-square/>
///
/// # Arguments:
/// * `matrix` - an array of integer array
///
/// # Complexity
/// - time complexity: O(n^2),
/// - space complexity: O(n),
pub fn maximal_square(matrix: &mut [Vec<i32>]) -> i32 {
if matrix.is_empty() {
return 0;
}
let rows = matrix.len();
let cols = matrix[0].len();
let mut result: i32 = 0;
for row in 0..rows {
for col in 0..cols {
if matrix[row][col] == 1 {
if row == 0 || col == 0 {
result = max(result, 1);
} else {
let temp = min(matrix[row - 1][col - 1], matrix[row - 1][col]);
let count: i32 = min(temp, matrix[row][col - 1]) + 1;
result = max(result, count);
matrix[row][col] = count;
}
}
}
}
result * result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
assert_eq!(maximal_square(&mut []), 0);
let mut matrix = vec![vec![0, 1], vec![1, 0]];
assert_eq!(maximal_square(&mut matrix), 1);
let mut matrix = vec![
vec![1, 0, 1, 0, 0],
vec![1, 0, 1, 1, 1],
vec![1, 1, 1, 1, 1],
vec![1, 0, 0, 1, 0],
];
assert_eq!(maximal_square(&mut matrix), 4);
let mut matrix = vec![vec![0]];
assert_eq!(maximal_square(&mut matrix), 0);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/rod_cutting.rs | src/dynamic_programming/rod_cutting.rs | //! This module provides functions for solving the rod-cutting problem using dynamic programming.
use std::cmp::max;
/// Calculates the maximum possible profit from cutting a rod into pieces of varying lengths.
///
/// Returns the maximum profit achievable by cutting a rod into pieces such that the profit from each
/// piece is determined by its length and predefined prices.
///
/// # Complexity
/// - Time complexity: `O(n^2)`
/// - Space complexity: `O(n)`
///
/// where `n` is the number of different rod lengths considered.
pub fn rod_cut(prices: &[usize]) -> usize {
if prices.is_empty() {
return 0;
}
(1..=prices.len()).fold(vec![0; prices.len() + 1], |mut max_profit, rod_length| {
max_profit[rod_length] = (1..=rod_length)
.map(|cut_position| prices[cut_position - 1] + max_profit[rod_length - cut_position])
.fold(prices[rod_length - 1], |max_price, current_price| {
max(max_price, current_price)
});
max_profit
})[prices.len()]
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! rod_cut_tests {
($($name:ident: $test_case:expr,)*) => {
$(
#[test]
fn $name() {
let (input, expected_output) = $test_case;
assert_eq!(expected_output, rod_cut(input));
}
)*
};
}
rod_cut_tests! {
test_empty_prices: (&[], 0),
test_example_with_three_prices: (&[5, 8, 2], 15),
test_example_with_four_prices: (&[1, 5, 8, 9], 10),
test_example_with_five_prices: (&[5, 8, 2, 1, 7], 25),
test_all_zeros_except_last: (&[0, 0, 0, 0, 0, 87], 87),
test_descending_prices: (&[7, 6, 5, 4, 3, 2, 1], 49),
test_varied_prices: (&[1, 5, 8, 9, 10, 17, 17, 20], 22),
test_complex_prices: (&[6, 4, 8, 2, 5, 8, 2, 3, 7, 11], 60),
test_increasing_prices: (&[1, 5, 8, 9, 10, 17, 17, 20, 24, 30], 30),
test_large_range_prices: (&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 12),
test_single_length_price: (&[5], 5),
test_zero_length_price: (&[0], 0),
test_repeated_prices: (&[5, 5, 5, 5], 20),
test_no_profit: (&[0, 0, 0, 0], 0),
test_large_input: (&[1; 1000], 1000),
test_all_zero_input: (&[0; 100], 0),
test_very_large_prices: (&[1000000, 2000000, 3000000], 3000000),
test_greedy_does_not_work: (&[2, 5, 7, 8], 10),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/word_break.rs | src/dynamic_programming/word_break.rs | use crate::data_structures::Trie;
/// Checks if a string can be segmented into a space-separated sequence
/// of one or more words from the given dictionary.
///
/// # Arguments
/// * `s` - The input string to be segmented.
/// * `word_dict` - A slice of words forming the dictionary.
///
/// # Returns
/// * `bool` - `true` if the string can be segmented, `false` otherwise.
pub fn word_break(s: &str, word_dict: &[&str]) -> bool {
let mut trie = Trie::new();
for &word in word_dict {
trie.insert(word.chars(), true);
}
// Memoization vector: one extra space to handle out-of-bound end case.
let mut memo = vec![None; s.len() + 1];
search(&trie, s, 0, &mut memo)
}
/// Recursively checks if the substring starting from `start` can be segmented
/// using words in the trie and memoizes the results.
///
/// # Arguments
/// * `trie` - The Trie containing the dictionary words.
/// * `s` - The input string.
/// * `start` - The starting index for the current substring.
/// * `memo` - A vector for memoization to store intermediate results.
///
/// # Returns
/// * `bool` - `true` if the substring can be segmented, `false` otherwise.
fn search(trie: &Trie<char, bool>, s: &str, start: usize, memo: &mut Vec<Option<bool>>) -> bool {
if start == s.len() {
return true;
}
if let Some(res) = memo[start] {
return res;
}
for end in start + 1..=s.len() {
if trie.get(s[start..end].chars()).is_some() && search(trie, s, end, memo) {
memo[start] = Some(true);
return true;
}
}
memo[start] = Some(false);
false
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_cases {
($($name:ident: $test_case:expr,)*) => {
$(
#[test]
fn $name() {
let (input, dict, expected) = $test_case;
assert_eq!(word_break(input, &dict), expected);
}
)*
}
}
test_cases! {
typical_case_1: ("applepenapple", vec!["apple", "pen"], true),
typical_case_2: ("catsandog", vec!["cats", "dog", "sand", "and", "cat"], false),
typical_case_3: ("cars", vec!["car", "ca", "rs"], true),
edge_case_empty_string: ("", vec!["apple", "pen"], true),
edge_case_empty_dict: ("apple", vec![], false),
edge_case_single_char_in_dict: ("a", vec!["a"], true),
edge_case_single_char_not_in_dict: ("b", vec!["a"], false),
edge_case_all_words_larger_than_input: ("a", vec!["apple", "banana"], false),
edge_case_no_solution_large_string: ("abcdefghijklmnoqrstuv", vec!["a", "bc", "def", "ghij", "klmno", "pqrst"], false),
successful_segmentation_large_string: ("abcdefghijklmnopqrst", vec!["a", "bc", "def", "ghij", "klmno", "pqrst"], true),
long_string_repeated_pattern: (&"ab".repeat(100), vec!["a", "b", "ab"], true),
long_string_no_solution: (&"a".repeat(100), vec!["b"], false),
mixed_size_dict_1: ("pineapplepenapple", vec!["apple", "pen", "applepen", "pine", "pineapple"], true),
mixed_size_dict_2: ("catsandog", vec!["cats", "dog", "sand", "and", "cat"], false),
mixed_size_dict_3: ("abcd", vec!["a", "abc", "b", "cd"], true),
performance_stress_test_large_valid: (&"abc".repeat(1000), vec!["a", "ab", "abc"], true),
performance_stress_test_large_invalid: (&"x".repeat(1000), vec!["a", "ab", "abc"], false),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/subset_generation.rs | src/dynamic_programming/subset_generation.rs | // list all subset combinations of n element in given set of r element.
// This is a recursive function that collects all subsets of the set of size n
// with the given set of size r.
pub fn list_subset(
set: &[i32],
n: usize,
r: usize,
index: usize,
data: &mut [i32],
i: usize,
) -> Vec<Vec<i32>> {
let mut res = Vec::new();
// Current subset is ready to be added to the list
if i == r {
let mut subset = Vec::new();
for j in data.iter().take(r) {
subset.push(*j);
}
res.push(subset);
return res;
}
// When no more elements are there to put in data[]
if index >= n {
return res;
}
// current is included, put next at next location
data[i] = set[index];
res.append(&mut list_subset(set, n, r, index + 1, data, i + 1));
// current is excluded, replace it with next (Note that
// i+1 is passed, but index is not changed)
res.append(&mut list_subset(set, n, r, index + 1, data, i));
res
}
// Test module
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_print_subset3() {
let set = [1, 2, 3, 4, 5];
let n = set.len();
const R: usize = 3;
let mut data = [0; R];
let res = list_subset(&set, n, R, 0, &mut data, 0);
assert_eq!(
res,
vec![
vec![1, 2, 3],
vec![1, 2, 4],
vec![1, 2, 5],
vec![1, 3, 4],
vec![1, 3, 5],
vec![1, 4, 5],
vec![2, 3, 4],
vec![2, 3, 5],
vec![2, 4, 5],
vec![3, 4, 5]
]
);
}
#[test]
fn test_print_subset4() {
let set = [1, 2, 3, 4, 5];
let n = set.len();
const R: usize = 4;
let mut data = [0; R];
let res = list_subset(&set, n, R, 0, &mut data, 0);
assert_eq!(
res,
vec![
vec![1, 2, 3, 4],
vec![1, 2, 3, 5],
vec![1, 2, 4, 5],
vec![1, 3, 4, 5],
vec![2, 3, 4, 5]
]
);
}
#[test]
fn test_print_subset5() {
let set = [1, 2, 3, 4, 5];
let n = set.len();
const R: usize = 5;
let mut data = [0; R];
let res = list_subset(&set, n, R, 0, &mut data, 0);
assert_eq!(res, vec![vec![1, 2, 3, 4, 5]]);
}
#[test]
fn test_print_incorrect_subset() {
let set = [1, 2, 3, 4, 5];
let n = set.len();
const R: usize = 6;
let mut data = [0; R];
let res = list_subset(&set, n, R, 0, &mut data, 0);
let result_set: Vec<Vec<i32>> = Vec::new();
assert_eq!(res, result_set);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/dynamic_programming/coin_change.rs | src/dynamic_programming/coin_change.rs | //! This module provides a solution to the coin change problem using dynamic programming.
//! The `coin_change` function calculates the fewest number of coins required to make up
//! a given amount using a specified set of coin denominations.
//!
//! The implementation leverages dynamic programming to build up solutions for smaller
//! amounts and combines them to solve for larger amounts. It ensures optimal substructure
//! and overlapping subproblems are efficiently utilized to achieve the solution.
//! # Complexity
//! - Time complexity: O(amount * coins.length)
//! - Space complexity: O(amount)
/// Returns the fewest number of coins needed to make up the given amount using the provided coin denominations.
/// If the amount cannot be made up by any combination of the coins, returns `None`.
///
/// # Arguments
/// * `coins` - A slice of coin denominations.
/// * `amount` - The total amount of money to be made up.
///
/// # Returns
/// * `Option<usize>` - The minimum number of coins required to make up the amount, or `None` if it's not possible.
///
/// # Complexity
/// * Time complexity: O(amount * coins.length)
/// * Space complexity: O(amount)
pub fn coin_change(coins: &[usize], amount: usize) -> Option<usize> {
let mut min_coins = vec![None; amount + 1];
min_coins[0] = Some(0);
(0..=amount).for_each(|curr_amount| {
coins
.iter()
.filter(|&&coin| curr_amount >= coin)
.for_each(|&coin| {
if let Some(prev_min_coins) = min_coins[curr_amount - coin] {
min_coins[curr_amount] = Some(
min_coins[curr_amount].map_or(prev_min_coins + 1, |curr_min_coins| {
curr_min_coins.min(prev_min_coins + 1)
}),
);
}
});
});
min_coins[amount]
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! coin_change_tests {
($($name:ident: $test_case:expr,)*) => {
$(
#[test]
fn $name() {
let (coins, amount, expected) = $test_case;
assert_eq!(expected, coin_change(&coins, amount));
}
)*
}
}
coin_change_tests! {
test_basic_case: (vec![1, 2, 5], 11, Some(3)),
test_multiple_denominations: (vec![2, 3, 5, 7, 11], 119, Some(12)),
test_empty_coins: (vec![], 1, None),
test_zero_amount: (vec![1, 2, 3], 0, Some(0)),
test_no_solution_small_coin: (vec![2], 3, None),
test_no_solution_large_coin: (vec![10, 20, 50, 100], 5, None),
test_single_coin_large_amount: (vec![1], 100, Some(100)),
test_large_amount_multiple_coins: (vec![1, 2, 5], 10000, Some(2000)),
test_no_combination_possible: (vec![3, 7], 5, None),
test_exact_combination: (vec![1, 3, 4], 6, Some(2)),
test_large_denomination_multiple_coins: (vec![10, 50, 100], 1000, Some(10)),
test_small_amount_not_possible: (vec![5, 10], 1, None),
test_non_divisible_amount: (vec![2], 3, None),
test_all_multiples: (vec![1, 2, 4, 8], 15, Some(4)),
test_large_amount_mixed_coins: (vec![1, 5, 10, 25], 999, Some(45)),
test_prime_coins_and_amount: (vec![2, 3, 5, 7], 17, Some(3)),
test_coins_larger_than_amount: (vec![5, 10, 20], 1, None),
test_repeating_denominations: (vec![1, 1, 1, 5], 8, Some(4)),
test_non_standard_denominations: (vec![1, 4, 6, 9], 15, Some(2)),
test_very_large_denominations: (vec![1000, 2000, 5000], 1, None),
test_large_amount_performance: (vec![1, 5, 10, 25, 50, 100, 200, 500], 9999, Some(29)),
test_powers_of_two: (vec![1, 2, 4, 8, 16, 32, 64], 127, Some(7)),
test_fibonacci_sequence: (vec![1, 2, 3, 5, 8, 13, 21, 34], 55, Some(2)),
test_mixed_small_large: (vec![1, 100, 1000, 10000], 11001, Some(3)),
test_impossible_combinations: (vec![2, 4, 6, 8], 7, None),
test_greedy_approach_does_not_work: (vec![1, 12, 20], 24, Some(2)),
test_zero_denominations_no_solution: (vec![0], 1, None),
test_zero_denominations_solution: (vec![0], 0, Some(0)),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/k_means.rs | src/machine_learning/k_means.rs | use rand::random;
fn get_distance(p1: &(f64, f64), p2: &(f64, f64)) -> f64 {
let dx: f64 = p1.0 - p2.0;
let dy: f64 = p1.1 - p2.1;
((dx * dx) + (dy * dy)).sqrt()
}
fn find_nearest(data_point: &(f64, f64), centroids: &[(f64, f64)]) -> u32 {
let mut cluster: u32 = 0;
for (i, c) in centroids.iter().enumerate() {
let d1 = get_distance(data_point, c);
let d2 = get_distance(data_point, ¢roids[cluster as usize]);
if d1 < d2 {
cluster = i as u32;
}
}
cluster
}
pub fn k_means(data_points: Vec<(f64, f64)>, n_clusters: usize, max_iter: i32) -> Option<Vec<u32>> {
if data_points.len() < n_clusters {
return None;
}
let mut centroids: Vec<(f64, f64)> = Vec::new();
let mut labels: Vec<u32> = vec![0; data_points.len()];
for _ in 0..n_clusters {
let x: f64 = random::<f64>();
let y: f64 = random::<f64>();
centroids.push((x, y));
}
let mut count_iter: i32 = 0;
while count_iter < max_iter {
let mut new_centroids_position: Vec<(f64, f64)> = vec![(0.0, 0.0); n_clusters];
let mut new_centroids_num: Vec<u32> = vec![0; n_clusters];
for (i, d) in data_points.iter().enumerate() {
let nearest_cluster = find_nearest(d, ¢roids);
labels[i] = nearest_cluster;
new_centroids_position[nearest_cluster as usize].0 += d.0;
new_centroids_position[nearest_cluster as usize].1 += d.1;
new_centroids_num[nearest_cluster as usize] += 1;
}
for i in 0..centroids.len() {
if new_centroids_num[i] == 0 {
continue;
}
let new_x: f64 = new_centroids_position[i].0 / new_centroids_num[i] as f64;
let new_y: f64 = new_centroids_position[i].1 / new_centroids_num[i] as f64;
centroids[i] = (new_x, new_y);
}
count_iter += 1;
}
Some(labels)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_k_means() {
let mut data_points: Vec<(f64, f64)> = vec![];
let n_points: usize = 1000;
for _ in 0..n_points {
let x: f64 = random::<f64>() * 100.0;
let y: f64 = random::<f64>() * 100.0;
data_points.push((x, y));
}
println!("{:?}", k_means(data_points, 10, 100).unwrap_or_default());
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/linear_regression.rs | src/machine_learning/linear_regression.rs | /// Returns the parameters of the line after performing simple linear regression on the input data.
pub fn linear_regression(data_points: Vec<(f64, f64)>) -> Option<(f64, f64)> {
if data_points.is_empty() {
return None;
}
let count = data_points.len() as f64;
let mean_x = data_points.iter().fold(0.0, |sum, y| sum + y.0) / count;
let mean_y = data_points.iter().fold(0.0, |sum, y| sum + y.1) / count;
let mut covariance = 0.0;
let mut std_dev_sqr_x = 0.0;
let mut std_dev_sqr_y = 0.0;
for data_point in data_points {
covariance += (data_point.0 - mean_x) * (data_point.1 - mean_y);
std_dev_sqr_x += (data_point.0 - mean_x).powi(2);
std_dev_sqr_y += (data_point.1 - mean_y).powi(2);
}
let std_dev_x = std_dev_sqr_x.sqrt();
let std_dev_y = std_dev_sqr_y.sqrt();
let std_dev_prod = std_dev_x * std_dev_y;
let pcc = covariance / std_dev_prod; //Pearson's correlation constant
let b = pcc * (std_dev_y / std_dev_x); //Slope of the line
let a = mean_y - b * mean_x; //Y-Intercept of the line
Some((a, b))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_linear_regression() {
assert_eq!(
linear_regression(vec![(0.0, 0.0), (1.0, 1.0), (2.0, 2.0)]),
Some((2.220446049250313e-16, 0.9999999999999998))
);
}
#[test]
fn test_empty_list_linear_regression() {
assert_eq!(linear_regression(vec![]), None);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/mod.rs | src/machine_learning/mod.rs | mod cholesky;
mod k_means;
mod linear_regression;
mod logistic_regression;
mod loss_function;
mod optimization;
pub use self::cholesky::cholesky;
pub use self::k_means::k_means;
pub use self::linear_regression::linear_regression;
pub use self::logistic_regression::logistic_regression;
pub use self::loss_function::average_margin_ranking_loss;
pub use self::loss_function::hng_loss;
pub use self::loss_function::huber_loss;
pub use self::loss_function::kld_loss;
pub use self::loss_function::mae_loss;
pub use self::loss_function::mse_loss;
pub use self::loss_function::neg_log_likelihood;
pub use self::optimization::gradient_descent;
pub use self::optimization::Adam;
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/logistic_regression.rs | src/machine_learning/logistic_regression.rs | use super::optimization::gradient_descent;
use std::f64::consts::E;
/// Returns the weights after performing Logistic regression on the input data points.
pub fn logistic_regression(
data_points: Vec<(Vec<f64>, f64)>,
iterations: usize,
learning_rate: f64,
) -> Option<Vec<f64>> {
if data_points.is_empty() {
return None;
}
let num_features = data_points[0].0.len() + 1;
let mut params = vec![0.0; num_features];
let derivative_fn = |params: &[f64]| derivative(params, &data_points);
gradient_descent(derivative_fn, &mut params, learning_rate, iterations as i32);
Some(params)
}
fn derivative(params: &[f64], data_points: &[(Vec<f64>, f64)]) -> Vec<f64> {
let num_features = params.len();
let mut gradients = vec![0.0; num_features];
for (features, y_i) in data_points {
let z = params[0]
+ params[1..]
.iter()
.zip(features)
.map(|(p, x)| p * x)
.sum::<f64>();
let prediction = 1.0 / (1.0 + E.powf(-z));
gradients[0] += prediction - y_i;
for (i, x_i) in features.iter().enumerate() {
gradients[i + 1] += (prediction - y_i) * x_i;
}
}
gradients
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_logistic_regression_simple() {
let data = vec![
(vec![0.0], 0.0),
(vec![1.0], 0.0),
(vec![2.0], 0.0),
(vec![3.0], 1.0),
(vec![4.0], 1.0),
(vec![5.0], 1.0),
];
let result = logistic_regression(data, 10000, 0.05);
assert!(result.is_some());
let params = result.unwrap();
assert!((params[0] + 17.65).abs() < 1.0);
assert!((params[1] - 7.13).abs() < 1.0);
}
#[test]
fn test_logistic_regression_extreme_data() {
let data = vec![
(vec![-100.0], 0.0),
(vec![-10.0], 0.0),
(vec![0.0], 0.0),
(vec![10.0], 1.0),
(vec![100.0], 1.0),
];
let result = logistic_regression(data, 10000, 0.05);
assert!(result.is_some());
let params = result.unwrap();
assert!((params[0] + 6.20).abs() < 1.0);
assert!((params[1] - 5.5).abs() < 1.0);
}
#[test]
fn test_logistic_regression_no_data() {
let result = logistic_regression(vec![], 5000, 0.1);
assert_eq!(result, None);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/cholesky.rs | src/machine_learning/cholesky.rs | pub fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
if (mat.is_empty()) || (n == 0) {
return vec![];
}
let mut res = vec![0.0; mat.len()];
for i in 0..n {
for j in 0..=i {
let mut s = 0.0;
for k in 0..j {
s += res[i * n + k] * res[j * n + k];
}
let value = if i == j {
let diag_value = mat[i * n + i] - s;
if diag_value.is_nan() {
0.0
} else {
diag_value.sqrt()
}
} else {
let off_diag_value = 1.0 / res[j * n + j] * (mat[i * n + j] - s);
if off_diag_value.is_nan() {
0.0
} else {
off_diag_value
}
};
res[i * n + j] = value;
}
}
res
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cholesky() {
// Test case 1
let mat1 = vec![25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0];
let res1 = cholesky(mat1, 3);
// The expected Cholesky decomposition values
#[allow(clippy::useless_vec)]
let expected1 = vec![5.0, 0.0, 0.0, 3.0, 3.0, 0.0, -1.0, 1.0, 3.0];
assert!(res1
.iter()
.zip(expected1.iter())
.all(|(a, b)| (a - b).abs() < 1e-6));
}
fn transpose_matrix(mat: &[f64], n: usize) -> Vec<f64> {
(0..n)
.flat_map(|i| (0..n).map(move |j| mat[j * n + i]))
.collect()
}
fn matrix_multiply(mat1: &[f64], mat2: &[f64], n: usize) -> Vec<f64> {
(0..n)
.flat_map(|i| {
(0..n).map(move |j| {
(0..n).fold(0.0, |acc, k| acc + mat1[i * n + k] * mat2[k * n + j])
})
})
.collect()
}
#[test]
fn test_matrix_operations() {
// Test case 1: Transposition
let mat1 = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0];
let transposed_mat1 = transpose_matrix(&mat1, 3);
let expected_transposed_mat1 = vec![1.0, 4.0, 7.0, 2.0, 5.0, 8.0, 3.0, 6.0, 9.0];
assert_eq!(transposed_mat1, expected_transposed_mat1);
// Test case 2: Matrix multiplication
let mat2 = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0];
let mat3 = vec![9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0];
let multiplied_mat = matrix_multiply(&mat2, &mat3, 3);
let expected_multiplied_mat = vec![30.0, 24.0, 18.0, 84.0, 69.0, 54.0, 138.0, 114.0, 90.0];
assert_eq!(multiplied_mat, expected_multiplied_mat);
}
#[test]
fn empty_matrix() {
let mat = vec![];
let res = cholesky(mat, 0);
assert_eq!(res, vec![]);
}
#[test]
fn matrix_with_all_zeros() {
let mat3 = vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
let res3 = cholesky(mat3, 3);
let expected3 = vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
assert_eq!(res3, expected3);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/optimization/momentum.rs | src/machine_learning/optimization/momentum.rs | /// Momentum Optimization
///
/// Momentum is an extension of gradient descent that accelerates convergence by accumulating
/// a velocity vector in directions of persistent reduction in the objective function.
/// This helps the optimizer navigate ravines and avoid getting stuck in local minima.
///
/// The algorithm maintains a velocity vector that accumulates exponentially decaying moving
/// averages of past gradients. This allows the optimizer to build up speed in consistent
/// directions while dampening oscillations.
///
/// The update equations are:
/// velocity_{k+1} = beta * velocity_k + gradient_of_function(x_k)
/// x_{k+1} = x_k - learning_rate * velocity_{k+1}
///
/// where beta (typically 0.9) controls how much past gradients influence the current update.
///
/// # Arguments
///
/// * `derivative_fn` - The function that calculates the gradient of the objective function at a given point.
/// * `x` - The initial parameter vector to be optimized.
/// * `learning_rate` - Step size for each iteration.
/// * `beta` - Momentum coefficient (typically 0.9). Higher values give more weight to past gradients.
/// * `num_iterations` - The number of iterations to run the optimization.
///
/// # Returns
///
/// A reference to the optimized parameter vector `x`.
#[allow(dead_code)]
pub fn momentum(
derivative: impl Fn(&[f64]) -> Vec<f64>,
x: &mut Vec<f64>,
learning_rate: f64,
beta: f64,
num_iterations: i32,
) -> &mut Vec<f64> {
// Initialize velocity vector to zero
let mut velocity: Vec<f64> = vec![0.0; x.len()];
for _ in 0..num_iterations {
let gradient = derivative(x);
// Update velocity and parameters
for ((x_k, vel), grad) in x.iter_mut().zip(velocity.iter_mut()).zip(gradient.iter()) {
*vel = beta * *vel + grad;
*x_k -= learning_rate * *vel;
}
}
x
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_momentum_optimized() {
fn derivative_of_square(params: &[f64]) -> Vec<f64> {
params.iter().map(|x| 2.0 * x).collect()
}
let mut x: Vec<f64> = vec![5.0, 6.0];
let learning_rate: f64 = 0.01;
let beta: f64 = 0.9;
let num_iterations: i32 = 1000;
let minimized_vector = momentum(
derivative_of_square,
&mut x,
learning_rate,
beta,
num_iterations,
);
let test_vector = [0.0, 0.0];
let tolerance = 1e-6;
for (minimized_value, test_value) in minimized_vector.iter().zip(test_vector.iter()) {
assert!((minimized_value - test_value).abs() < tolerance);
}
}
#[test]
fn test_momentum_unoptimized() {
fn derivative_of_square(params: &[f64]) -> Vec<f64> {
params.iter().map(|x| 2.0 * x).collect()
}
let mut x: Vec<f64> = vec![5.0, 6.0];
let learning_rate: f64 = 0.01;
let beta: f64 = 0.9;
let num_iterations: i32 = 10;
let minimized_vector = momentum(
derivative_of_square,
&mut x,
learning_rate,
beta,
num_iterations,
);
let test_vector = [0.0, 0.0];
let tolerance = 1e-6;
for (minimized_value, test_value) in minimized_vector.iter().zip(test_vector.iter()) {
assert!((minimized_value - test_value).abs() >= tolerance);
}
}
#[test]
fn test_momentum_faster_than_gd() {
fn derivative_of_square(params: &[f64]) -> Vec<f64> {
params.iter().map(|x| 2.0 * x).collect()
}
// Test that momentum converges faster than gradient descent
let mut x_momentum: Vec<f64> = vec![5.0, 6.0];
let mut x_gd: Vec<f64> = vec![5.0, 6.0];
let learning_rate: f64 = 0.01;
let beta: f64 = 0.9;
let num_iterations: i32 = 50;
momentum(
derivative_of_square,
&mut x_momentum,
learning_rate,
beta,
num_iterations,
);
// Gradient descent from your original implementation
for _ in 0..num_iterations {
let gradient = derivative_of_square(&x_gd);
for (x_k, grad) in x_gd.iter_mut().zip(gradient.iter()) {
*x_k -= learning_rate * grad;
}
}
// Momentum should be closer to zero
let momentum_distance: f64 = x_momentum.iter().map(|x| x * x).sum();
let gd_distance: f64 = x_gd.iter().map(|x| x * x).sum();
assert!(momentum_distance < gd_distance);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/optimization/adam.rs | src/machine_learning/optimization/adam.rs | //! # Adam (Adaptive Moment Estimation) optimizer
//!
//! The `Adam (Adaptive Moment Estimation)` optimizer is an adaptive learning rate algorithm used
//! in gradient descent and machine learning, such as for training neural networks to solve deep
//! learning problems. Boasting memory-efficient fast convergence rates, it sets and iteratively
//! updates learning rates individually for each model parameter based on the gradient history.
//!
//! ## Algorithm:
//!
//! Given:
//! - α is the learning rate
//! - (β_1, β_2) are the exponential decay rates for moment estimates
//! - ϵ is any small value to prevent division by zero
//! - g_t are the gradients at time step t
//! - m_t are the biased first moment estimates of the gradient at time step t
//! - v_t are the biased second raw moment estimates of the gradient at time step t
//! - θ_t are the model parameters at time step t
//! - t is the time step
//!
//! Required:
//! θ_0
//!
//! Initialize:
//! m_0 <- 0
//! v_0 <- 0
//! t <- 0
//!
//! while θ_t not converged do
//! m_t = β_1 * m_{t−1} + (1 − β_1) * g_t
//! v_t = β_2 * v_{t−1} + (1 − β_2) * g_t^2
//! m_hat_t = m_t / 1 - β_1^t
//! v_hat_t = v_t / 1 - β_2^t
//! θ_t = θ_{t-1} − α * m_hat_t / (sqrt(v_hat_t) + ϵ)
//!
//! ## Resources:
//! - Adam: A Method for Stochastic Optimization (by Diederik P. Kingma and Jimmy Ba):
//! - [https://arxiv.org/abs/1412.6980]
//! - PyTorch Adam optimizer:
//! - [https://pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam]
//!
pub struct Adam {
learning_rate: f64, // alpha: initial step size for iterative optimization
betas: (f64, f64), // betas: exponential decay rates for moment estimates
epsilon: f64, // epsilon: prevent division by zero
m: Vec<f64>, // m: biased first moment estimate of the gradient vector
v: Vec<f64>, // v: biased second raw moment estimate of the gradient vector
t: usize, // t: time step
}
impl Adam {
pub fn new(
learning_rate: Option<f64>,
betas: Option<(f64, f64)>,
epsilon: Option<f64>,
params_len: usize,
) -> Self {
Adam {
learning_rate: learning_rate.unwrap_or(1e-3), // typical good default lr
betas: betas.unwrap_or((0.9, 0.999)), // typical good default decay rates
epsilon: epsilon.unwrap_or(1e-8), // typical good default epsilon
m: vec![0.0; params_len], // first moment vector elements all initialized to zero
v: vec![0.0; params_len], // second moment vector elements all initialized to zero
t: 0, // time step initialized to zero
}
}
pub fn step(&mut self, gradients: &[f64]) -> Vec<f64> {
let mut model_params = vec![0.0; gradients.len()];
self.t += 1;
for i in 0..gradients.len() {
// update biased first moment estimate and second raw moment estimate
self.m[i] = self.betas.0 * self.m[i] + (1.0 - self.betas.0) * gradients[i];
self.v[i] = self.betas.1 * self.v[i] + (1.0 - self.betas.1) * gradients[i].powf(2f64);
// compute bias-corrected first moment estimate and second raw moment estimate
let m_hat = self.m[i] / (1.0 - self.betas.0.powi(self.t as i32));
let v_hat = self.v[i] / (1.0 - self.betas.1.powi(self.t as i32));
// update model parameters
model_params[i] -= self.learning_rate * m_hat / (v_hat.sqrt() + self.epsilon);
}
model_params // return updated model parameters
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_adam_init_default_values() {
let optimizer = Adam::new(None, None, None, 1);
assert_eq!(optimizer.learning_rate, 0.001);
assert_eq!(optimizer.betas, (0.9, 0.999));
assert_eq!(optimizer.epsilon, 1e-8);
assert_eq!(optimizer.m, vec![0.0; 1]);
assert_eq!(optimizer.v, vec![0.0; 1]);
assert_eq!(optimizer.t, 0);
}
#[test]
fn test_adam_init_custom_lr_value() {
let optimizer = Adam::new(Some(0.9), None, None, 2);
assert_eq!(optimizer.learning_rate, 0.9);
assert_eq!(optimizer.betas, (0.9, 0.999));
assert_eq!(optimizer.epsilon, 1e-8);
assert_eq!(optimizer.m, vec![0.0; 2]);
assert_eq!(optimizer.v, vec![0.0; 2]);
assert_eq!(optimizer.t, 0);
}
#[test]
fn test_adam_init_custom_betas_value() {
let optimizer = Adam::new(None, Some((0.8, 0.899)), None, 3);
assert_eq!(optimizer.learning_rate, 0.001);
assert_eq!(optimizer.betas, (0.8, 0.899));
assert_eq!(optimizer.epsilon, 1e-8);
assert_eq!(optimizer.m, vec![0.0; 3]);
assert_eq!(optimizer.v, vec![0.0; 3]);
assert_eq!(optimizer.t, 0);
}
#[test]
fn test_adam_init_custom_epsilon_value() {
let optimizer = Adam::new(None, None, Some(1e-10), 4);
assert_eq!(optimizer.learning_rate, 0.001);
assert_eq!(optimizer.betas, (0.9, 0.999));
assert_eq!(optimizer.epsilon, 1e-10);
assert_eq!(optimizer.m, vec![0.0; 4]);
assert_eq!(optimizer.v, vec![0.0; 4]);
assert_eq!(optimizer.t, 0);
}
#[test]
fn test_adam_init_all_custom_values() {
let optimizer = Adam::new(Some(1.0), Some((0.001, 0.099)), Some(1e-1), 5);
assert_eq!(optimizer.learning_rate, 1.0);
assert_eq!(optimizer.betas, (0.001, 0.099));
assert_eq!(optimizer.epsilon, 1e-1);
assert_eq!(optimizer.m, vec![0.0; 5]);
assert_eq!(optimizer.v, vec![0.0; 5]);
assert_eq!(optimizer.t, 0);
}
#[test]
fn test_adam_step_default_params() {
let gradients = vec![-1.0, 2.0, -3.0, 4.0, -5.0, 6.0, -7.0, 8.0];
let mut optimizer = Adam::new(None, None, None, 8);
let updated_params = optimizer.step(&gradients);
assert_eq!(
updated_params,
vec![
0.0009999999900000003,
-0.000999999995,
0.0009999999966666666,
-0.0009999999975,
0.000999999998,
-0.0009999999983333334,
0.0009999999985714286,
-0.00099999999875
]
);
}
#[test]
fn test_adam_step_custom_params() {
let gradients = vec![9.0, -8.0, 7.0, -6.0, 5.0, -4.0, 3.0, -2.0, 1.0];
let mut optimizer = Adam::new(Some(0.005), Some((0.5, 0.599)), Some(1e-5), 9);
let updated_params = optimizer.step(&gradients);
assert_eq!(
updated_params,
vec![
-0.004999994444450618,
0.004999993750007813,
-0.004999992857153062,
0.004999991666680556,
-0.004999990000020001,
0.004999987500031251,
-0.004999983333388888,
0.004999975000124999,
-0.0049999500004999945
]
);
}
#[test]
fn test_adam_step_empty_gradients_array() {
let gradients = vec![];
let mut optimizer = Adam::new(None, None, None, 0);
let updated_params = optimizer.step(&gradients);
assert_eq!(updated_params, vec![]);
}
#[ignore]
#[test]
fn test_adam_step_iteratively_until_convergence_with_default_params() {
const CONVERGENCE_THRESHOLD: f64 = 1e-5;
let gradients = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
let mut optimizer = Adam::new(None, None, None, 6);
let mut model_params = vec![0.0; 6];
let mut updated_params = optimizer.step(&gradients);
while (updated_params
.iter()
.zip(model_params.iter())
.map(|(x, y)| x - y)
.collect::<Vec<f64>>())
.iter()
.map(|&x| x.powi(2))
.sum::<f64>()
.sqrt()
> CONVERGENCE_THRESHOLD
{
model_params = updated_params;
updated_params = optimizer.step(&gradients);
}
assert!(updated_params < vec![CONVERGENCE_THRESHOLD; 6]);
assert_ne!(updated_params, model_params);
assert_eq!(
updated_params,
vec![
-0.0009999999899999931,
-0.0009999999949999929,
-0.0009999999966666597,
-0.0009999999974999929,
-0.0009999999979999927,
-0.0009999999983333263
]
);
}
#[ignore]
#[test]
fn test_adam_step_iteratively_until_convergence_with_custom_params() {
const CONVERGENCE_THRESHOLD: f64 = 1e-7;
let gradients = vec![7.0, -8.0, 9.0, -10.0, 11.0, -12.0, 13.0];
let mut optimizer = Adam::new(Some(0.005), Some((0.8, 0.899)), Some(1e-5), 7);
let mut model_params = vec![0.0; 7];
let mut updated_params = optimizer.step(&gradients);
while (updated_params
.iter()
.zip(model_params.iter())
.map(|(x, y)| x - y)
.collect::<Vec<f64>>())
.iter()
.map(|&x| x.powi(2))
.sum::<f64>()
.sqrt()
> CONVERGENCE_THRESHOLD
{
model_params = updated_params;
updated_params = optimizer.step(&gradients);
}
assert!(updated_params < vec![CONVERGENCE_THRESHOLD; 7]);
assert_ne!(updated_params, model_params);
assert_eq!(
updated_params,
vec![
-0.004999992857153061,
0.004999993750007814,
-0.0049999944444506185,
0.004999995000005001,
-0.004999995454549587,
0.004999995833336807,
-0.004999996153849113
]
);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/optimization/gradient_descent.rs | src/machine_learning/optimization/gradient_descent.rs | /// Gradient Descent Optimization
///
/// Gradient descent is an iterative optimization algorithm used to find the minimum of a function.
/// It works by updating the parameters (in this case, elements of the vector `x`) in the direction of
/// the steepest decrease in the function's value. This is achieved by subtracting the gradient of
/// the function at the current point from the current point. The learning rate controls the step size.
///
/// The equation for a single parameter (univariate) is:
/// x_{k+1} = x_k - learning_rate * derivative_of_function(x_k)
///
/// For multivariate functions, it extends to each parameter:
/// x_{k+1} = x_k - learning_rate * gradient_of_function(x_k)
///
/// # Arguments
///
/// * `derivative_fn` - The function that calculates the gradient of the objective function at a given point.
/// * `x` - The initial parameter vector to be optimized.
/// * `learning_rate` - Step size for each iteration.
/// * `num_iterations` - The number of iterations to run the optimization.
///
/// # Returns
///
/// A reference to the optimized parameter vector `x`.
pub fn gradient_descent(
derivative_fn: impl Fn(&[f64]) -> Vec<f64>,
x: &mut Vec<f64>,
learning_rate: f64,
num_iterations: i32,
) -> &mut Vec<f64> {
for _ in 0..num_iterations {
let gradient = derivative_fn(x);
for (x_k, grad) in x.iter_mut().zip(gradient.iter()) {
*x_k -= learning_rate * grad;
}
}
x
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_gradient_descent_optimized() {
fn derivative_of_square(params: &[f64]) -> Vec<f64> {
params.iter().map(|x| 2. * x).collect()
}
let mut x: Vec<f64> = vec![5.0, 6.0];
let learning_rate: f64 = 0.03;
let num_iterations: i32 = 1000;
let minimized_vector =
gradient_descent(derivative_of_square, &mut x, learning_rate, num_iterations);
let test_vector = [0.0, 0.0];
let tolerance = 1e-6;
for (minimized_value, test_value) in minimized_vector.iter().zip(test_vector.iter()) {
assert!((minimized_value - test_value).abs() < tolerance);
}
}
#[test]
fn test_gradient_descent_unoptimized() {
fn derivative_of_square(params: &[f64]) -> Vec<f64> {
params.iter().map(|x| 2. * x).collect()
}
let mut x: Vec<f64> = vec![5.0, 6.0];
let learning_rate: f64 = 0.03;
let num_iterations: i32 = 10;
let minimized_vector =
gradient_descent(derivative_of_square, &mut x, learning_rate, num_iterations);
let test_vector = [0.0, 0.0];
let tolerance = 1e-6;
for (minimized_value, test_value) in minimized_vector.iter().zip(test_vector.iter()) {
assert!((minimized_value - test_value).abs() >= tolerance);
}
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/optimization/mod.rs | src/machine_learning/optimization/mod.rs | mod adam;
mod gradient_descent;
mod momentum;
pub use self::adam::Adam;
pub use self::gradient_descent::gradient_descent;
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/loss_function/negative_log_likelihood.rs | src/machine_learning/loss_function/negative_log_likelihood.rs | // Negative Log Likelihood Loss Function
//
// The `neg_log_likelihood` function calculates the Negative Log Likelyhood loss,
// which is a loss function used for classification problems in machine learning.
//
// ## Formula
//
// For a pair of actual and predicted values, represented as vectors `y_true` and
// `y_pred`, the Negative Log Likelihood loss is calculated as:
//
// - loss = `-y_true * log(y_pred) - (1 - y_true) * log(1 - y_pred)`.
//
// It returns the average loss by dividing the `total_loss` by total no. of
// elements.
//
// https://towardsdatascience.com/cross-entropy-negative-log-likelihood-and-all-that-jazz-47a95bd2e81
// http://neuralnetworksanddeeplearning.com/chap3.html
// Derivation of the formula:
// https://medium.com/@bhardwajprakarsh/negative-log-likelihood-loss-why-do-we-use-it-for-binary-classification-7625f9e3c944
pub fn neg_log_likelihood(
y_true: &[f64],
y_pred: &[f64],
) -> Result<f64, NegativeLogLikelihoodLossError> {
// Checks if the inputs are empty
if y_true.len() != y_pred.len() {
return Err(NegativeLogLikelihoodLossError::InputsHaveDifferentLength);
}
// Checks if the length of the actual and predicted values are equal
if y_pred.is_empty() {
return Err(NegativeLogLikelihoodLossError::EmptyInputs);
}
// Checks values are between 0 and 1
if !are_all_values_in_range(y_true) || !are_all_values_in_range(y_pred) {
return Err(NegativeLogLikelihoodLossError::InvalidValues);
}
let mut total_loss: f64 = 0.0;
for (p, a) in y_pred.iter().zip(y_true.iter()) {
let loss: f64 = -a * p.ln() - (1.0 - a) * (1.0 - p).ln();
total_loss += loss;
}
Ok(total_loss / (y_pred.len() as f64))
}
#[derive(Debug, PartialEq, Eq)]
pub enum NegativeLogLikelihoodLossError {
InputsHaveDifferentLength,
EmptyInputs,
InvalidValues,
}
fn are_all_values_in_range(values: &[f64]) -> bool {
values.iter().all(|&x| (0.0..=1.0).contains(&x))
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_with_wrong_inputs {
($($name:ident: $inputs:expr,)*) => {
$(
#[test]
fn $name() {
let (values_a, values_b, expected_error) = $inputs;
assert_eq!(neg_log_likelihood(&values_a, &values_b), expected_error);
assert_eq!(neg_log_likelihood(&values_b, &values_a), expected_error);
}
)*
}
}
test_with_wrong_inputs! {
different_length: (vec![0.9, 0.0, 0.8], vec![0.9, 0.1], Err(NegativeLogLikelihoodLossError::InputsHaveDifferentLength)),
different_length_one_empty: (vec![], vec![0.9, 0.1], Err(NegativeLogLikelihoodLossError::InputsHaveDifferentLength)),
value_greater_than_1: (vec![1.1, 0.0, 0.8], vec![0.1, 0.2, 0.3], Err(NegativeLogLikelihoodLossError::InvalidValues)),
value_greater_smaller_than_0: (vec![0.9, 0.0, -0.1], vec![0.1, 0.2, 0.3], Err(NegativeLogLikelihoodLossError::InvalidValues)),
empty_input: (vec![], vec![], Err(NegativeLogLikelihoodLossError::EmptyInputs)),
}
macro_rules! test_neg_log_likelihood {
($($name:ident: $inputs:expr,)*) => {
$(
#[test]
fn $name() {
let (actual_values, predicted_values, expected) = $inputs;
assert_eq!(neg_log_likelihood(&actual_values, &predicted_values).unwrap(), expected);
}
)*
}
}
test_neg_log_likelihood! {
set_0: (vec![1.0, 0.0, 1.0], vec![0.9, 0.1, 0.8], 0.14462152754328741),
set_1: (vec![1.0, 0.0, 1.0], vec![0.1, 0.2, 0.3], 1.2432338162113972),
set_2: (vec![0.0, 1.0, 0.0], vec![0.1, 0.2, 0.3], 0.6904911240102196),
set_3: (vec![1.0, 0.0, 1.0, 0.0], vec![0.9, 0.1, 0.8, 0.2], 0.164252033486018),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/loss_function/kl_divergence_loss.rs | src/machine_learning/loss_function/kl_divergence_loss.rs | //! # KL divergence Loss Function
//!
//! For a pair of actual and predicted probability distributions represented as vectors `actual` and `predicted`, the KL divergence loss is calculated as:
//!
//! `L = -Σ(actual[i] * ln(predicted[i]/actual[i]))` for all `i` in the range of the vectors
//!
//! Where `ln` is the natural logarithm function, and `Σ` denotes the summation over all elements of the vectors.
//!
//! ## KL divergence Loss Function Implementation
//!
//! This implementation takes two references to vectors of f64 values, `actual` and `predicted`, and returns the KL divergence loss between them.
//!
pub fn kld_loss(actual: &[f64], predicted: &[f64]) -> f64 {
// epsilon to handle if any of the elements are zero
let eps = 0.00001f64;
let loss: f64 = actual
.iter()
.zip(predicted.iter())
.map(|(&a, &p)| (a + eps) * ((a + eps) / (p + eps)).ln())
.sum();
loss
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_kld_loss() {
let test_vector_actual = vec![1.346112, 1.337432, 1.246655];
let test_vector = vec![1.033836, 1.082015, 1.117323];
assert_eq!(
kld_loss(&test_vector_actual, &test_vector),
0.7752789394328498
);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/loss_function/huber_loss.rs | src/machine_learning/loss_function/huber_loss.rs | /// Computes the Huber loss between arrays of true and predicted values.
///
/// # Arguments
///
/// * `y_true` - An array of true values.
/// * `y_pred` - An array of predicted values.
/// * `delta` - The threshold parameter that controls the linear behavior of the loss function.
///
/// # Returns
///
/// The average Huber loss for all pairs of true and predicted values.
pub fn huber_loss(y_true: &[f64], y_pred: &[f64], delta: f64) -> Option<f64> {
if y_true.len() != y_pred.len() || y_pred.is_empty() {
return None;
}
let loss: f64 = y_true
.iter()
.zip(y_pred.iter())
.map(|(&true_val, &pred_val)| {
let residual = (true_val - pred_val).abs();
match residual {
r if r <= delta => 0.5 * r.powi(2),
_ => delta * residual - 0.5 * delta.powi(2),
}
})
.sum();
Some(loss / (y_pred.len() as f64))
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! huber_loss_tests {
($($name:ident: $test_case:expr,)*) => {
$(
#[test]
fn $name() {
let (y_true, y_pred, delta, expected_loss) = $test_case;
assert_eq!(huber_loss(&y_true, &y_pred, delta), expected_loss);
}
)*
};
}
huber_loss_tests! {
test_huber_loss_residual_less_than_delta: (
vec![10.0, 8.0, 12.0],
vec![9.0, 7.0, 11.0],
1.0,
Some(0.5)
),
test_huber_loss_residual_greater_than_delta: (
vec![3.0, 5.0, 7.0],
vec![2.0, 4.0, 8.0],
0.5,
Some(0.375)
),
test_huber_loss_invalid_length: (
vec![10.0, 8.0, 12.0],
vec![7.0, 6.0],
1.0,
None
),
test_huber_loss_empty_prediction: (
vec![10.0, 8.0, 12.0],
vec![],
1.0,
None
),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/loss_function/mean_absolute_error_loss.rs | src/machine_learning/loss_function/mean_absolute_error_loss.rs | //! # Mean Absolute Error Loss Function
//!
//! The `mae_loss` function calculates the Mean Absolute Error loss, which is a
//! robust loss function used in machine learning.
//!
//! ## Formula
//!
//! For a pair of actual and predicted values, represented as vectors `actual`
//! and `predicted`, the Mean Absolute loss is calculated as:
//!
//! - loss = `(actual - predicted) / n_elements`.
//!
//! It returns the average loss by dividing the `total_loss` by total no. of
//! elements.
//!
pub fn mae_loss(predicted: &[f64], actual: &[f64]) -> f64 {
let mut total_loss: f64 = 0.0;
for (p, a) in predicted.iter().zip(actual.iter()) {
let diff: f64 = p - a;
let absolute_diff = diff.abs();
total_loss += absolute_diff;
}
total_loss / (predicted.len() as f64)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mae_loss() {
let predicted_values: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0];
let actual_values: Vec<f64> = vec![1.0, 3.0, 3.5, 4.5];
assert_eq!(mae_loss(&predicted_values, &actual_values), 0.5);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/loss_function/hinge_loss.rs | src/machine_learning/loss_function/hinge_loss.rs | //! # Hinge Loss
//!
//! The `hng_loss` function calculates the Hinge loss, which is a
//! loss function used for classification problems in machine learning.
//!
//! ## Formula
//!
//! For a pair of actual and predicted values, represented as vectors `y_true` and
//! `y_pred`, the Hinge loss is calculated as:
//!
//! - loss = `max(0, 1 - y_true * y_pred)`.
//!
//! It returns the average loss by dividing the `total_loss` by total no. of
//! elements.
//!
pub fn hng_loss(y_true: &[f64], y_pred: &[f64]) -> f64 {
let mut total_loss: f64 = 0.0;
for (p, a) in y_pred.iter().zip(y_true.iter()) {
let loss = (1.0 - a * p).max(0.0);
total_loss += loss;
}
total_loss / (y_pred.len() as f64)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hinge_loss() {
let predicted_values: Vec<f64> = vec![-1.0, 1.0, 1.0];
let actual_values: Vec<f64> = vec![-1.0, -1.0, 1.0];
assert_eq!(
hng_loss(&predicted_values, &actual_values),
0.6666666666666666
);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/loss_function/average_margin_ranking_loss.rs | src/machine_learning/loss_function/average_margin_ranking_loss.rs | /// Marginal Ranking
///
/// The 'average_margin_ranking_loss' function calculates the Margin Ranking loss, which is a
/// loss function used for ranking problems in machine learning.
///
/// ## Formula
///
/// For a pair of values `x_first` and `x_second`, `margin`, and `y_true`,
/// the Margin Ranking loss is calculated as:
///
/// - loss = `max(0, -y_true * (x_first - x_second) + margin)`.
///
/// It returns the average loss by dividing the `total_loss` by total no. of
/// elements.
///
/// Pytorch implementation:
/// https://pytorch.org/docs/stable/generated/torch.nn.MarginRankingLoss.html
/// https://gombru.github.io/2019/04/03/ranking_loss/
/// https://vinija.ai/concepts/loss/#pairwise-ranking-loss
///
pub fn average_margin_ranking_loss(
x_first: &[f64],
x_second: &[f64],
margin: f64,
y_true: f64,
) -> Result<f64, MarginalRankingLossError> {
check_input(x_first, x_second, margin, y_true)?;
let total_loss: f64 = x_first
.iter()
.zip(x_second.iter())
.map(|(f, s)| (margin - y_true * (f - s)).max(0.0))
.sum();
Ok(total_loss / (x_first.len() as f64))
}
fn check_input(
x_first: &[f64],
x_second: &[f64],
margin: f64,
y_true: f64,
) -> Result<(), MarginalRankingLossError> {
if x_first.len() != x_second.len() {
return Err(MarginalRankingLossError::InputsHaveDifferentLength);
}
if x_first.is_empty() {
return Err(MarginalRankingLossError::EmptyInputs);
}
if margin < 0.0 {
return Err(MarginalRankingLossError::NegativeMargin);
}
if y_true != 1.0 && y_true != -1.0 {
return Err(MarginalRankingLossError::InvalidValues);
}
Ok(())
}
#[derive(Debug, PartialEq, Eq)]
pub enum MarginalRankingLossError {
InputsHaveDifferentLength,
EmptyInputs,
InvalidValues,
NegativeMargin,
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_with_wrong_inputs {
($($name:ident: $inputs:expr,)*) => {
$(
#[test]
fn $name() {
let (vec_a, vec_b, margin, y_true, expected) = $inputs;
assert_eq!(average_margin_ranking_loss(&vec_a, &vec_b, margin, y_true), expected);
assert_eq!(average_margin_ranking_loss(&vec_b, &vec_a, margin, y_true), expected);
}
)*
}
}
test_with_wrong_inputs! {
invalid_length0: (vec![1.0, 2.0, 3.0], vec![2.0, 3.0], 1.0, 1.0, Err(MarginalRankingLossError::InputsHaveDifferentLength)),
invalid_length1: (vec![1.0, 2.0], vec![2.0, 3.0, 4.0], 1.0, 1.0, Err(MarginalRankingLossError::InputsHaveDifferentLength)),
invalid_length2: (vec![], vec![1.0, 2.0, 3.0], 1.0, 1.0, Err(MarginalRankingLossError::InputsHaveDifferentLength)),
invalid_length3: (vec![1.0, 2.0, 3.0], vec![], 1.0, 1.0, Err(MarginalRankingLossError::InputsHaveDifferentLength)),
invalid_values: (vec![1.0, 2.0, 3.0], vec![2.0, 3.0, 4.0], -1.0, 1.0, Err(MarginalRankingLossError::NegativeMargin)),
invalid_y_true: (vec![1.0, 2.0, 3.0], vec![2.0, 3.0, 4.0], 1.0, 2.0, Err(MarginalRankingLossError::InvalidValues)),
empty_inputs: (vec![], vec![], 1.0, 1.0, Err(MarginalRankingLossError::EmptyInputs)),
}
macro_rules! test_average_margin_ranking_loss {
($($name:ident: $inputs:expr,)*) => {
$(
#[test]
fn $name() {
let (x_first, x_second, margin, y_true, expected) = $inputs;
assert_eq!(average_margin_ranking_loss(&x_first, &x_second, margin, y_true), Ok(expected));
}
)*
}
}
test_average_margin_ranking_loss! {
set_0: (vec![1.0, 2.0, 3.0], vec![2.0, 3.0, 4.0], 1.0, -1.0, 0.0),
set_1: (vec![1.0, 2.0, 3.0], vec![2.0, 3.0, 4.0], 1.0, 1.0, 2.0),
set_2: (vec![1.0, 2.0, 3.0], vec![1.0, 2.0, 3.0], 0.0, 1.0, 0.0),
set_3: (vec![4.0, 5.0, 6.0], vec![1.0, 2.0, 3.0], 1.0, -1.0, 4.0),
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/loss_function/mod.rs | src/machine_learning/loss_function/mod.rs | mod average_margin_ranking_loss;
mod hinge_loss;
mod huber_loss;
mod kl_divergence_loss;
mod mean_absolute_error_loss;
mod mean_squared_error_loss;
mod negative_log_likelihood;
pub use self::average_margin_ranking_loss::average_margin_ranking_loss;
pub use self::hinge_loss::hng_loss;
pub use self::huber_loss::huber_loss;
pub use self::kl_divergence_loss::kld_loss;
pub use self::mean_absolute_error_loss::mae_loss;
pub use self::mean_squared_error_loss::mse_loss;
pub use self::negative_log_likelihood::neg_log_likelihood;
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/machine_learning/loss_function/mean_squared_error_loss.rs | src/machine_learning/loss_function/mean_squared_error_loss.rs | //! # Mean Square Loss Function
//!
//! The `mse_loss` function calculates the Mean Square Error loss, which is a
//! robust loss function used in machine learning.
//!
//! ## Formula
//!
//! For a pair of actual and predicted values, represented as vectors `actual`
//! and `predicted`, the Mean Square loss is calculated as:
//!
//! - loss = `(actual - predicted)^2 / n_elements`.
//!
//! It returns the average loss by dividing the `total_loss` by total no. of
//! elements.
//!
pub fn mse_loss(predicted: &[f64], actual: &[f64]) -> f64 {
let mut total_loss: f64 = 0.0;
for (p, a) in predicted.iter().zip(actual.iter()) {
let diff: f64 = p - a;
total_loss += diff * diff;
}
total_loss / (predicted.len() as f64)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mse_loss() {
let predicted_values: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0];
let actual_values: Vec<f64> = vec![1.0, 3.0, 3.5, 4.5];
assert_eq!(mse_loss(&predicted_values, &actual_values), 0.375);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/union_find.rs | src/data_structures/union_find.rs | //! A Union-Find (Disjoint Set) data structure implementation in Rust.
//!
//! The Union-Find data structure keeps track of elements partitioned into
//! disjoint (non-overlapping) sets.
//! It provides near-constant-time operations to add new sets, to find the
//! representative of a set, and to merge sets.
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
#[derive(Debug)]
pub struct UnionFind<T: Debug + Eq + Hash> {
payloads: HashMap<T, usize>, // Maps values to their indices in the parent_links array.
parent_links: Vec<usize>, // Holds the parent pointers; root elements are their own parents.
sizes: Vec<usize>, // Holds the sizes of the sets.
count: usize, // Number of disjoint sets.
}
impl<T: Debug + Eq + Hash> UnionFind<T> {
/// Creates an empty Union-Find structure with a specified capacity.
pub fn with_capacity(capacity: usize) -> Self {
Self {
parent_links: Vec::with_capacity(capacity),
sizes: Vec::with_capacity(capacity),
payloads: HashMap::with_capacity(capacity),
count: 0,
}
}
/// Inserts a new item (disjoint set) into the data structure.
pub fn insert(&mut self, item: T) {
let key = self.payloads.len();
self.parent_links.push(key);
self.sizes.push(1);
self.payloads.insert(item, key);
self.count += 1;
}
/// Returns the root index of the set containing the given value, or `None` if it doesn't exist.
pub fn find(&mut self, value: &T) -> Option<usize> {
self.payloads
.get(value)
.copied()
.map(|key| self.find_by_key(key))
}
/// Unites the sets containing the two given values. Returns:
/// - `None` if either value hasn't been inserted,
/// - `Some(true)` if two disjoint sets have been merged,
/// - `Some(false)` if both elements were already in the same set.
pub fn union(&mut self, first_item: &T, sec_item: &T) -> Option<bool> {
let (first_root, sec_root) = (self.find(first_item), self.find(sec_item));
match (first_root, sec_root) {
(Some(first_root), Some(sec_root)) => Some(self.union_by_key(first_root, sec_root)),
_ => None,
}
}
/// Finds the root of the set containing the element with the given index.
fn find_by_key(&mut self, key: usize) -> usize {
if self.parent_links[key] != key {
self.parent_links[key] = self.find_by_key(self.parent_links[key]);
}
self.parent_links[key]
}
/// Unites the sets containing the two elements identified by their indices.
fn union_by_key(&mut self, first_key: usize, sec_key: usize) -> bool {
let (first_root, sec_root) = (self.find_by_key(first_key), self.find_by_key(sec_key));
if first_root == sec_root {
return false;
}
match self.sizes[first_root].cmp(&self.sizes[sec_root]) {
Ordering::Less => {
self.parent_links[first_root] = sec_root;
self.sizes[sec_root] += self.sizes[first_root];
}
_ => {
self.parent_links[sec_root] = first_root;
self.sizes[first_root] += self.sizes[sec_root];
}
}
self.count -= 1;
true
}
/// Checks if two items belong to the same set.
pub fn is_same_set(&mut self, first_item: &T, sec_item: &T) -> bool {
matches!((self.find(first_item), self.find(sec_item)), (Some(first_root), Some(sec_root)) if first_root == sec_root)
}
/// Returns the number of disjoint sets.
pub fn count(&self) -> usize {
self.count
}
}
impl<T: Debug + Eq + Hash> Default for UnionFind<T> {
fn default() -> Self {
Self {
parent_links: Vec::default(),
sizes: Vec::default(),
payloads: HashMap::default(),
count: 0,
}
}
}
impl<T: Debug + Eq + Hash> FromIterator<T> for UnionFind<T> {
/// Creates a new UnionFind data structure from an iterable of disjoint elements.
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut uf = UnionFind::default();
for item in iter {
uf.insert(item);
}
uf
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_union_find() {
let mut uf = (0..10).collect::<UnionFind<_>>();
assert_eq!(uf.find(&0), Some(0));
assert_eq!(uf.find(&1), Some(1));
assert_eq!(uf.find(&2), Some(2));
assert_eq!(uf.find(&3), Some(3));
assert_eq!(uf.find(&4), Some(4));
assert_eq!(uf.find(&5), Some(5));
assert_eq!(uf.find(&6), Some(6));
assert_eq!(uf.find(&7), Some(7));
assert_eq!(uf.find(&8), Some(8));
assert_eq!(uf.find(&9), Some(9));
assert!(!uf.is_same_set(&0, &1));
assert!(!uf.is_same_set(&2, &9));
assert_eq!(uf.count(), 10);
assert_eq!(uf.union(&0, &1), Some(true));
assert_eq!(uf.union(&1, &2), Some(true));
assert_eq!(uf.union(&2, &3), Some(true));
assert_eq!(uf.union(&0, &2), Some(false));
assert_eq!(uf.union(&4, &5), Some(true));
assert_eq!(uf.union(&5, &6), Some(true));
assert_eq!(uf.union(&6, &7), Some(true));
assert_eq!(uf.union(&7, &8), Some(true));
assert_eq!(uf.union(&8, &9), Some(true));
assert_eq!(uf.union(&7, &9), Some(false));
assert_ne!(uf.find(&0), uf.find(&9));
assert_eq!(uf.find(&0), uf.find(&3));
assert_eq!(uf.find(&4), uf.find(&9));
assert!(uf.is_same_set(&0, &3));
assert!(uf.is_same_set(&4, &9));
assert!(!uf.is_same_set(&0, &9));
assert_eq!(uf.count(), 2);
assert_eq!(Some(true), uf.union(&3, &4));
assert_eq!(uf.find(&0), uf.find(&9));
assert_eq!(uf.count(), 1);
assert!(uf.is_same_set(&0, &9));
assert_eq!(None, uf.union(&0, &11));
}
#[test]
fn test_spanning_tree() {
let mut uf = UnionFind::from_iter(["A", "B", "C", "D", "E", "F", "G"]);
uf.union(&"A", &"B");
uf.union(&"B", &"C");
uf.union(&"A", &"D");
uf.union(&"F", &"G");
assert_eq!(None, uf.union(&"A", &"W"));
assert_eq!(uf.find(&"A"), uf.find(&"B"));
assert_eq!(uf.find(&"A"), uf.find(&"C"));
assert_eq!(uf.find(&"B"), uf.find(&"D"));
assert_ne!(uf.find(&"A"), uf.find(&"E"));
assert_ne!(uf.find(&"A"), uf.find(&"F"));
assert_eq!(uf.find(&"G"), uf.find(&"F"));
assert_ne!(uf.find(&"G"), uf.find(&"E"));
assert!(uf.is_same_set(&"A", &"B"));
assert!(uf.is_same_set(&"A", &"C"));
assert!(uf.is_same_set(&"B", &"D"));
assert!(!uf.is_same_set(&"B", &"F"));
assert!(!uf.is_same_set(&"E", &"A"));
assert!(!uf.is_same_set(&"E", &"G"));
assert_eq!(uf.count(), 3);
}
#[test]
fn test_with_capacity() {
let mut uf: UnionFind<i32> = UnionFind::with_capacity(5);
uf.insert(0);
uf.insert(1);
uf.insert(2);
uf.insert(3);
uf.insert(4);
assert_eq!(uf.count(), 5);
assert_eq!(uf.union(&0, &1), Some(true));
assert!(uf.is_same_set(&0, &1));
assert_eq!(uf.count(), 4);
assert_eq!(uf.union(&2, &3), Some(true));
assert!(uf.is_same_set(&2, &3));
assert_eq!(uf.count(), 3);
assert_eq!(uf.union(&0, &2), Some(true));
assert!(uf.is_same_set(&0, &1));
assert!(uf.is_same_set(&2, &3));
assert!(uf.is_same_set(&0, &3));
assert_eq!(uf.count(), 2);
assert_eq!(None, uf.union(&0, &10));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/floyds_algorithm.rs | src/data_structures/floyds_algorithm.rs | // floyds_algorithm.rs
// https://github.com/rust-lang/rust/blob/master/library/alloc/src/collections/linked_list.rs#L113
// use std::collections::linked_list::LinkedList;
// https://www.reddit.com/r/rust/comments/t7wquc/is_it_possible_to_solve_leetcode_problem141/
use crate::data_structures::linked_list::LinkedList; // Import the LinkedList from linked_list.rs
pub fn detect_cycle<T>(linked_list: &LinkedList<T>) -> Option<usize> {
let mut current = linked_list.head;
let mut checkpoint = linked_list.head;
let mut steps_until_reset = 1;
let mut times_reset = 0;
while let Some(node) = current {
steps_until_reset -= 1;
if steps_until_reset == 0 {
checkpoint = current;
times_reset += 1;
steps_until_reset = 1 << times_reset; // 2^times_reset
}
unsafe {
let node_ptr = node.as_ptr();
let next = (*node_ptr).next;
current = next;
}
if current == checkpoint {
return Some(linked_list.length as usize);
}
}
None
}
pub fn has_cycle<T>(linked_list: &LinkedList<T>) -> bool {
let mut slow = linked_list.head;
let mut fast = linked_list.head;
while let (Some(slow_node), Some(fast_node)) = (slow, fast) {
unsafe {
slow = slow_node.as_ref().next;
fast = fast_node.as_ref().next;
if let Some(fast_next) = fast {
// fast = (*fast_next.as_ptr()).next;
fast = fast_next.as_ref().next;
} else {
return false; // If fast reaches the end, there's no cycle
}
if slow == fast {
return true; // Cycle detected
}
}
}
// println!("{}", flag);
false // No cycle detected
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_detect_cycle_no_cycle() {
let mut linked_list = LinkedList::new();
linked_list.insert_at_tail(1);
linked_list.insert_at_tail(2);
linked_list.insert_at_tail(3);
assert!(!has_cycle(&linked_list));
assert_eq!(detect_cycle(&linked_list), None);
}
#[test]
fn test_detect_cycle_with_cycle() {
let mut linked_list = LinkedList::new();
linked_list.insert_at_tail(1);
linked_list.insert_at_tail(2);
linked_list.insert_at_tail(3);
// Create a cycle for testing
unsafe {
if let Some(mut tail) = linked_list.tail {
if let Some(head) = linked_list.head {
tail.as_mut().next = Some(head);
}
}
}
assert!(has_cycle(&linked_list));
assert_eq!(detect_cycle(&linked_list), Some(3));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/stack_using_singly_linked_list.rs | src/data_structures/stack_using_singly_linked_list.rs | // The public struct can hide the implementation detail
pub struct Stack<T> {
head: Link<T>,
}
type Link<T> = Option<Box<Node<T>>>;
struct Node<T> {
elem: T,
next: Link<T>,
}
impl<T> Stack<T> {
// Self is an alias for Stack
// We implement associated function name new for single-linked-list
pub fn new() -> Self {
// for new function we need to return a new instance
Self {
// we refer to variants of an enum using :: the namespacing operator
head: None,
} // we need to return the variant, so there without the ;
}
// Here are the primary forms that self can take are: self, &mut self and &self.
// Since push will modify the linked list, we need a mutable reference `&mut`.
// The push method which the signature's first parameter is self
pub fn push(&mut self, elem: T) {
let new_node = Box::new(Node {
elem,
next: self.head.take(),
});
// don't forget replace the head with new node for stack
self.head = Some(new_node);
}
/// The pop function removes the head and returns its value.
///
/// To do so, we'll need to match the `head` of the list, which is of enum type `Option<T>`.\
/// It has two variants: `Some(T)` and `None`.
/// * `None` - the list is empty:
/// * return an enum `Result` of variant `Err()`, as there is nothing to pop.
/// * `Some(node)` - the list is not empty:
/// * remove the head of the list,
/// * relink the list's head `head` to its following node `next`,
/// * return `Ok(elem)`.
pub fn pop(&mut self) -> Result<T, &str> {
match self.head.take() {
None => Err("Stack is empty"),
Some(node) => {
self.head = node.next;
Ok(node.elem)
}
}
}
pub fn is_empty(&self) -> bool {
// Returns true if head is of variant `None`.
self.head.is_none()
}
pub fn peek(&self) -> Option<&T> {
// Converts from &Option<T> to Option<&T>.
match self.head.as_ref() {
None => None,
Some(node) => Some(&node.elem),
}
}
pub fn peek_mut(&mut self) -> Option<&mut T> {
match self.head.as_mut() {
None => None,
Some(node) => Some(&mut node.elem),
}
}
pub fn into_iter_for_stack(self) -> IntoIter<T> {
IntoIter(self)
}
pub fn iter(&self) -> Iter<'_, T> {
Iter {
next: self.head.as_deref(),
}
}
// '_ is the "explicitly elided lifetime" syntax of Rust
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
IterMut {
next: self.head.as_deref_mut(),
}
}
}
impl<T> Default for Stack<T> {
fn default() -> Self {
Self::new()
}
}
/// The drop method of singly linked list.
///
/// Here's a question: *Do we need to worry about cleaning up our list?*\
/// With the help of the ownership mechanism, the type `List` will be cleaned up automatically (dropped) after it goes out of scope.\
/// The Rust Compiler does so automacally. In other words, the `Drop` trait is implemented automatically.\
///
/// The `Drop` trait is implemented for our type `List` with the following order: `List->Link->Box<Node>->Node`.\
/// The `.drop()` method is tail recursive and will clean the element one by one, this recursion will stop at `Box<Node>`\
/// <https://rust-unofficial.github.io/too-many-lists/first-drop.html>
///
/// We wouldn't be able to drop the contents contained by the box after deallocating, so we need to manually write the iterative drop.
impl<T> Drop for Stack<T> {
fn drop(&mut self) {
let mut cur_link = self.head.take();
while let Some(mut boxed_node) = cur_link {
cur_link = boxed_node.next.take();
// boxed_node goes out of scope and gets dropped here;
// but its Node's `next` field has been set to None
// so no unbound recursion occurs.
}
}
}
// Rust has nothing like a yield statement, and there are actually 3 different iterator traits to be implemented
// Collections are iterated in Rust using the Iterator trait, we define a struct implement Iterator
pub struct IntoIter<T>(Stack<T>);
impl<T> Iterator for IntoIter<T> {
// This is declaring that every implementation of iterator has an associated type called Item
type Item = T;
// the reason iterator yield Option<self::Item> is because the interface coalesces the `has_next` and `get_next` concepts
fn next(&mut self) -> Option<Self::Item> {
self.0.pop().ok()
}
}
pub struct Iter<'a, T> {
next: Option<&'a Node<T>>,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|node| {
// as_deref: Converts from Option<T> (or &Option<T>) to Option<&T::Target>.
self.next = node.next.as_deref();
&node.elem
})
}
}
pub struct IterMut<'a, T> {
next: Option<&'a mut Node<T>>,
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
// we add take() here due to &mut self isn't Copy(& and Option<&> is Copy)
self.next.take().map(|node| {
self.next = node.next.as_deref_mut();
&mut node.elem
})
}
}
#[cfg(test)]
mod test_stack {
use super::*;
#[test]
fn basics() {
let mut list = Stack::new();
assert_eq!(list.pop(), Err("Stack is empty"));
list.push(1);
list.push(2);
list.push(3);
assert_eq!(list.pop(), Ok(3));
assert_eq!(list.pop(), Ok(2));
list.push(4);
list.push(5);
assert!(!list.is_empty());
assert_eq!(list.pop(), Ok(5));
assert_eq!(list.pop(), Ok(4));
assert_eq!(list.pop(), Ok(1));
assert_eq!(list.pop(), Err("Stack is empty"));
assert!(list.is_empty());
}
#[test]
fn peek() {
let mut list = Stack::new();
assert_eq!(list.peek(), None);
list.push(1);
list.push(2);
list.push(3);
assert_eq!(list.peek(), Some(&3));
assert_eq!(list.peek_mut(), Some(&mut 3));
match list.peek_mut() {
None => (),
Some(value) => *value = 42,
};
assert_eq!(list.peek(), Some(&42));
assert_eq!(list.pop(), Ok(42));
}
#[test]
fn into_iter() {
let mut list = Stack::new();
list.push(1);
list.push(2);
list.push(3);
let mut iter = list.into_iter_for_stack();
assert_eq!(iter.next(), Some(3));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), None);
}
#[test]
fn iter() {
let mut list = Stack::new();
list.push(1);
list.push(2);
list.push(3);
let mut iter = list.iter();
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&1));
}
#[test]
fn iter_mut() {
let mut list = Stack::new();
list.push(1);
list.push(2);
list.push(3);
let mut iter = list.iter_mut();
assert_eq!(iter.next(), Some(&mut 3));
assert_eq!(iter.next(), Some(&mut 2));
assert_eq!(iter.next(), Some(&mut 1));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/treap.rs | src/data_structures/treap.rs | use std::{
cmp::Ordering,
iter::FromIterator,
mem,
ops::Not,
time::{SystemTime, UNIX_EPOCH},
};
/// An internal node of an `Treap`.
struct TreapNode<T: Ord> {
value: T,
priority: usize,
left: Option<Box<TreapNode<T>>>,
right: Option<Box<TreapNode<T>>>,
}
/// A set based on a Treap (Randomized Binary Search Tree).
///
/// A Treap is a self-balancing binary search tree. It matains a priority value for each node, such
/// that for every node, its children will have lower priority than itself. So, by just looking at
/// the priority, it is like a heap, and this is where the name, Treap, comes from, Tree + Heap.
pub struct Treap<T: Ord> {
root: Option<Box<TreapNode<T>>>,
length: usize,
}
/// Refers to the left or right subtree of a `Treap`.
#[derive(Clone, Copy)]
enum Side {
Left,
Right,
}
impl<T: Ord> Treap<T> {
pub fn new() -> Treap<T> {
Treap {
root: None,
length: 0,
}
}
/// Returns `true` if the tree contains a value.
pub fn contains(&self, value: &T) -> bool {
let mut current = &self.root;
while let Some(node) = current {
current = match value.cmp(&node.value) {
Ordering::Equal => return true,
Ordering::Less => &node.left,
Ordering::Greater => &node.right,
}
}
false
}
/// Adds a value to the tree
///
/// Returns `true` if the tree did not yet contain the value.
pub fn insert(&mut self, value: T) -> bool {
let inserted = insert(&mut self.root, value);
if inserted {
self.length += 1;
}
inserted
}
/// Removes a value from the tree.
///
/// Returns `true` if the tree contained the value.
pub fn remove(&mut self, value: &T) -> bool {
let removed = remove(&mut self.root, value);
if removed {
self.length -= 1;
}
removed
}
/// Returns the number of values in the tree.
pub fn len(&self) -> usize {
self.length
}
/// Returns `true` if the tree contains no values.
pub fn is_empty(&self) -> bool {
self.length == 0
}
/// Returns an iterator that visits the nodes in the tree in order.
fn node_iter(&self) -> NodeIter<'_, T> {
let mut node_iter = NodeIter { stack: Vec::new() };
// Initialize stack with path to leftmost child
let mut child = &self.root;
while let Some(node) = child {
node_iter.stack.push(node.as_ref());
child = &node.left;
}
node_iter
}
/// Returns an iterator that visits the values in the tree in ascending order.
pub fn iter(&self) -> Iter<'_, T> {
Iter {
node_iter: self.node_iter(),
}
}
}
/// Generating random number, should use rand::Rng if possible.
fn rand() -> usize {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.subsec_nanos() as usize
}
/// Recursive helper function for `Treap` insertion.
fn insert<T: Ord>(tree: &mut Option<Box<TreapNode<T>>>, value: T) -> bool {
if let Some(node) = tree {
let inserted = match value.cmp(&node.value) {
Ordering::Equal => false,
Ordering::Less => insert(&mut node.left, value),
Ordering::Greater => insert(&mut node.right, value),
};
if inserted {
node.rebalance();
}
inserted
} else {
*tree = Some(Box::new(TreapNode {
value,
priority: rand(),
left: None,
right: None,
}));
true
}
}
/// Recursive helper function for `Treap` deletion
fn remove<T: Ord>(tree: &mut Option<Box<TreapNode<T>>>, value: &T) -> bool {
if let Some(node) = tree {
let removed = match value.cmp(&node.value) {
Ordering::Less => remove(&mut node.left, value),
Ordering::Greater => remove(&mut node.right, value),
Ordering::Equal => {
*tree = match (node.left.take(), node.right.take()) {
(None, None) => None,
(Some(b), None) | (None, Some(b)) => Some(b),
(Some(left), Some(right)) => {
let side = match left.priority.cmp(&right.priority) {
Ordering::Greater => Side::Right,
_ => Side::Left,
};
node.left = Some(left);
node.right = Some(right);
node.rotate(side);
remove(node.child_mut(side), value);
Some(tree.take().unwrap())
}
};
return true;
}
};
if removed {
node.rebalance();
}
removed
} else {
false
}
}
impl<T: Ord> TreapNode<T> {
/// Returns a reference to the left or right child.
fn child(&self, side: Side) -> &Option<Box<TreapNode<T>>> {
match side {
Side::Left => &self.left,
Side::Right => &self.right,
}
}
/// Returns a mutable reference to the left or right child.
fn child_mut(&mut self, side: Side) -> &mut Option<Box<TreapNode<T>>> {
match side {
Side::Left => &mut self.left,
Side::Right => &mut self.right,
}
}
/// Returns the priority of the left or right subtree.
fn priority(&self, side: Side) -> usize {
self.child(side).as_ref().map_or(0, |n| n.priority)
}
/// Performs a left or right rotation
fn rotate(&mut self, side: Side) {
if self.child_mut(!side).is_none() {
return;
}
let mut subtree = self.child_mut(!side).take().unwrap();
*self.child_mut(!side) = subtree.child_mut(side).take();
// Swap root and child nodes in memory
mem::swap(self, subtree.as_mut());
// Set old root (subtree) as child of new root (self)
*self.child_mut(side) = Some(subtree);
}
/// Performs left or right tree rotations to balance this node.
fn rebalance(&mut self) {
match (
self.priority,
self.priority(Side::Left),
self.priority(Side::Right),
) {
(v, p, q) if p >= q && p > v => self.rotate(Side::Right),
(v, p, q) if p < q && q > v => self.rotate(Side::Left),
_ => (),
};
}
#[cfg(test)]
fn is_valid(&self) -> bool {
self.priority >= self.priority(Side::Left) && self.priority >= self.priority(Side::Right)
}
}
impl<T: Ord> Default for Treap<T> {
fn default() -> Self {
Self::new()
}
}
impl Not for Side {
type Output = Side;
fn not(self) -> Self::Output {
match self {
Side::Left => Side::Right,
Side::Right => Side::Left,
}
}
}
impl<T: Ord> FromIterator<T> for Treap<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut tree = Treap::new();
for value in iter {
tree.insert(value);
}
tree
}
}
/// An iterator over the nodes of an `Treap`.
///
/// This struct is created by the `node_iter` method of `Treap`.
struct NodeIter<'a, T: Ord> {
stack: Vec<&'a TreapNode<T>>,
}
impl<'a, T: Ord> Iterator for NodeIter<'a, T> {
type Item = &'a TreapNode<T>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(node) = self.stack.pop() {
// Push left path of right subtree to stack
let mut child = &node.right;
while let Some(subtree) = child {
self.stack.push(subtree.as_ref());
child = &subtree.left;
}
Some(node)
} else {
None
}
}
}
/// An iterator over the items of an `Treap`.
///
/// This struct is created by the `iter` method of `Treap`.
pub struct Iter<'a, T: Ord> {
node_iter: NodeIter<'a, T>,
}
impl<'a, T: Ord> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
match self.node_iter.next() {
Some(node) => Some(&node.value),
None => None,
}
}
}
#[cfg(test)]
mod tests {
use super::Treap;
/// Returns `true` if all nodes in the tree are valid.
fn is_valid<T: Ord>(tree: &Treap<T>) -> bool {
tree.node_iter().all(|n| n.is_valid())
}
#[test]
fn len() {
let tree: Treap<_> = (1..4).collect();
assert_eq!(tree.len(), 3);
}
#[test]
fn contains() {
let tree: Treap<_> = (1..4).collect();
assert!(tree.contains(&1));
assert!(!tree.contains(&4));
}
#[test]
fn insert() {
let mut tree = Treap::new();
// First insert succeeds
assert!(tree.insert(1));
// Second insert fails
assert!(!tree.insert(1));
}
#[test]
fn remove() {
let mut tree: Treap<_> = (1..8).collect();
// First remove succeeds
assert!(tree.remove(&4));
// Second remove fails
assert!(!tree.remove(&4));
}
#[test]
fn sorted() {
let tree: Treap<_> = (1..8).rev().collect();
assert!((1..8).eq(tree.iter().copied()));
}
#[test]
fn valid() {
let mut tree: Treap<_> = (1..8).collect();
assert!(is_valid(&tree));
for x in 1..8 {
tree.remove(&x);
assert!(is_valid(&tree));
}
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/b_tree.rs | src/data_structures/b_tree.rs | use std::convert::TryFrom;
use std::fmt::Debug;
use std::mem;
struct Node<T> {
keys: Vec<T>,
children: Vec<Node<T>>,
}
pub struct BTree<T> {
root: Node<T>,
props: BTreeProps,
}
// Why to need a different Struct for props...
// Check - http://smallcultfollowing.com/babysteps/blog/2018/11/01/after-nll-interprocedural-conflicts/#fnref:improvement
struct BTreeProps {
degree: usize,
max_keys: usize,
mid_key_index: usize,
}
impl<T> Node<T>
where
T: Ord,
{
fn new(degree: usize, _keys: Option<Vec<T>>, _children: Option<Vec<Node<T>>>) -> Self {
Node {
keys: match _keys {
Some(_keys) => _keys,
None => Vec::with_capacity(degree - 1),
},
children: match _children {
Some(_children) => _children,
None => Vec::with_capacity(degree),
},
}
}
fn is_leaf(&self) -> bool {
self.children.is_empty()
}
}
impl BTreeProps {
fn new(degree: usize) -> Self {
BTreeProps {
degree,
max_keys: degree - 1,
mid_key_index: (degree - 1) / 2,
}
}
fn is_maxed_out<T: Ord + Copy>(&self, node: &Node<T>) -> bool {
node.keys.len() == self.max_keys
}
// Split Child expects the Child Node to be full
/// Move the middle_key to parent node and split the child_node's
/// keys/chilren_nodes into half
fn split_child<T: Ord + Copy + Default>(&self, parent: &mut Node<T>, child_index: usize) {
let child = &mut parent.children[child_index];
let middle_key = child.keys[self.mid_key_index];
let right_keys = match child.keys.split_off(self.mid_key_index).split_first() {
Some((_first, _others)) => {
// We don't need _first, as it will move to parent node.
_others.to_vec()
}
None => Vec::with_capacity(self.max_keys),
};
let right_children = if child.is_leaf() {
None
} else {
Some(child.children.split_off(self.mid_key_index + 1))
};
let new_child_node: Node<T> = Node::new(self.degree, Some(right_keys), right_children);
parent.keys.insert(child_index, middle_key);
parent.children.insert(child_index + 1, new_child_node);
}
fn insert_non_full<T: Ord + Copy + Default>(&mut self, node: &mut Node<T>, key: T) {
let mut index: isize = isize::try_from(node.keys.len()).ok().unwrap() - 1;
while index >= 0 && node.keys[index as usize] >= key {
index -= 1;
}
let mut u_index: usize = usize::try_from(index + 1).ok().unwrap();
if node.is_leaf() {
// Just insert it, as we know this method will be called only when node is not full
node.keys.insert(u_index, key);
} else {
if self.is_maxed_out(&node.children[u_index]) {
self.split_child(node, u_index);
if node.keys[u_index] < key {
u_index += 1;
}
}
self.insert_non_full(&mut node.children[u_index], key);
}
}
fn traverse_node<T: Ord + Debug>(node: &Node<T>, depth: usize) {
if node.is_leaf() {
print!(" {0:{<1$}{2:?}{0:}<1$} ", "", depth, node.keys);
} else {
let _depth = depth + 1;
for (index, key) in node.keys.iter().enumerate() {
Self::traverse_node(&node.children[index], _depth);
// Check https://doc.rust-lang.org/std/fmt/index.html
// And https://stackoverflow.com/a/35280799/2849127
print!("{0:{<1$}{2:?}{0:}<1$}", "", depth, key);
}
Self::traverse_node(node.children.last().unwrap(), _depth);
}
}
}
impl<T> BTree<T>
where
T: Ord + Copy + Debug + Default,
{
pub fn new(branch_factor: usize) -> Self {
let degree = 2 * branch_factor;
BTree {
root: Node::new(degree, None, None),
props: BTreeProps::new(degree),
}
}
pub fn insert(&mut self, key: T) {
if self.props.is_maxed_out(&self.root) {
// Create an empty root and split the old root...
let mut new_root = Node::new(self.props.degree, None, None);
mem::swap(&mut new_root, &mut self.root);
self.root.children.insert(0, new_root);
self.props.split_child(&mut self.root, 0);
}
self.props.insert_non_full(&mut self.root, key);
}
pub fn traverse(&self) {
BTreeProps::traverse_node(&self.root, 0);
println!();
}
pub fn search(&self, key: T) -> bool {
let mut current_node = &self.root;
loop {
match current_node.keys.binary_search(&key) {
Ok(_) => return true,
Err(index) => {
if current_node.is_leaf() {
return false;
}
current_node = ¤t_node.children[index];
}
}
}
}
}
#[cfg(test)]
mod test {
use super::BTree;
macro_rules! test_search {
($($name:ident: $number_of_children:expr,)*) => {
$(
#[test]
fn $name() {
let mut tree = BTree::new($number_of_children);
tree.insert(10);
tree.insert(20);
tree.insert(30);
tree.insert(5);
tree.insert(6);
tree.insert(7);
tree.insert(11);
tree.insert(12);
tree.insert(15);
assert!(!tree.search(4));
assert!(tree.search(5));
assert!(tree.search(6));
assert!(tree.search(7));
assert!(!tree.search(8));
assert!(!tree.search(9));
assert!(tree.search(10));
assert!(tree.search(11));
assert!(tree.search(12));
assert!(!tree.search(13));
assert!(!tree.search(14));
assert!(tree.search(15));
assert!(!tree.search(16));
}
)*
}
}
test_search! {
children_2: 2,
children_3: 3,
children_4: 4,
children_5: 5,
children_10: 10,
children_60: 60,
children_101: 101,
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/binary_search_tree.rs | src/data_structures/binary_search_tree.rs | use std::cmp::Ordering;
use std::ops::Deref;
/// This struct implements as Binary Search Tree (BST), which is a
/// simple data structure for storing sorted data
pub struct BinarySearchTree<T>
where
T: Ord,
{
value: Option<T>,
left: Option<Box<BinarySearchTree<T>>>,
right: Option<Box<BinarySearchTree<T>>>,
}
impl<T> Default for BinarySearchTree<T>
where
T: Ord,
{
fn default() -> Self {
Self::new()
}
}
impl<T> BinarySearchTree<T>
where
T: Ord,
{
/// Create a new, empty BST
pub fn new() -> BinarySearchTree<T> {
BinarySearchTree {
value: None,
left: None,
right: None,
}
}
/// Find a value in this tree. Returns True if value is in this
/// tree, and false otherwise
pub fn search(&self, value: &T) -> bool {
match &self.value {
Some(key) => {
match key.cmp(value) {
Ordering::Equal => {
// key == value
true
}
Ordering::Greater => {
// key > value
match &self.left {
Some(node) => node.search(value),
None => false,
}
}
Ordering::Less => {
// key < value
match &self.right {
Some(node) => node.search(value),
None => false,
}
}
}
}
None => false,
}
}
/// Returns a new iterator which iterates over this tree in order
pub fn iter(&self) -> impl Iterator<Item = &T> {
BinarySearchTreeIter::new(self)
}
/// Insert a value into the appropriate location in this tree.
pub fn insert(&mut self, value: T) {
match &self.value {
None => self.value = Some(value),
Some(key) => {
let target_node = if value < *key {
&mut self.left
} else {
&mut self.right
};
match target_node {
Some(ref mut node) => {
node.insert(value);
}
None => {
let mut node = BinarySearchTree::new();
node.value = Some(value);
*target_node = Some(Box::new(node));
}
}
}
}
}
/// Returns the smallest value in this tree
pub fn minimum(&self) -> Option<&T> {
match &self.left {
Some(node) => node.minimum(),
None => self.value.as_ref(),
}
}
/// Returns the largest value in this tree
pub fn maximum(&self) -> Option<&T> {
match &self.right {
Some(node) => node.maximum(),
None => self.value.as_ref(),
}
}
/// Returns the largest value in this tree smaller than value
pub fn floor(&self, value: &T) -> Option<&T> {
match &self.value {
Some(key) => {
match key.cmp(value) {
Ordering::Greater => {
// key > value
match &self.left {
Some(node) => node.floor(value),
None => None,
}
}
Ordering::Less => {
// key < value
match &self.right {
Some(node) => {
let val = node.floor(value);
match val {
Some(_) => val,
None => Some(key),
}
}
None => Some(key),
}
}
Ordering::Equal => Some(key),
}
}
None => None,
}
}
/// Returns the smallest value in this tree larger than value
pub fn ceil(&self, value: &T) -> Option<&T> {
match &self.value {
Some(key) => {
match key.cmp(value) {
Ordering::Less => {
// key < value
match &self.right {
Some(node) => node.ceil(value),
None => None,
}
}
Ordering::Greater => {
// key > value
match &self.left {
Some(node) => {
let val = node.ceil(value);
match val {
Some(_) => val,
None => Some(key),
}
}
None => Some(key),
}
}
Ordering::Equal => {
// key == value
Some(key)
}
}
}
None => None,
}
}
}
struct BinarySearchTreeIter<'a, T>
where
T: Ord,
{
stack: Vec<&'a BinarySearchTree<T>>,
}
impl<T> BinarySearchTreeIter<'_, T>
where
T: Ord,
{
pub fn new(tree: &BinarySearchTree<T>) -> BinarySearchTreeIter<'_, T> {
let mut iter = BinarySearchTreeIter { stack: vec![tree] };
iter.stack_push_left();
iter
}
fn stack_push_left(&mut self) {
while let Some(child) = &self.stack.last().unwrap().left {
self.stack.push(child);
}
}
}
impl<'a, T> Iterator for BinarySearchTreeIter<'a, T>
where
T: Ord,
{
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
if self.stack.is_empty() {
None
} else {
let node = self.stack.pop().unwrap();
if node.right.is_some() {
self.stack.push(node.right.as_ref().unwrap().deref());
self.stack_push_left();
}
node.value.as_ref()
}
}
}
#[cfg(test)]
mod test {
use super::BinarySearchTree;
fn prequel_memes_tree() -> BinarySearchTree<&'static str> {
let mut tree = BinarySearchTree::new();
tree.insert("hello there");
tree.insert("general kenobi");
tree.insert("you are a bold one");
tree.insert("kill him");
tree.insert("back away...I will deal with this jedi slime myself");
tree.insert("your move");
tree.insert("you fool");
tree
}
#[test]
fn test_search() {
let tree = prequel_memes_tree();
assert!(tree.search(&"hello there"));
assert!(tree.search(&"you are a bold one"));
assert!(tree.search(&"general kenobi"));
assert!(tree.search(&"you fool"));
assert!(tree.search(&"kill him"));
assert!(
!tree.search(&"but i was going to tosche station to pick up some power converters",)
);
assert!(!tree.search(&"only a sith deals in absolutes"));
assert!(!tree.search(&"you underestimate my power"));
}
#[test]
fn test_maximum_and_minimum() {
let tree = prequel_memes_tree();
assert_eq!(*tree.maximum().unwrap(), "your move");
assert_eq!(
*tree.minimum().unwrap(),
"back away...I will deal with this jedi slime myself"
);
let mut tree2: BinarySearchTree<i32> = BinarySearchTree::new();
assert!(tree2.maximum().is_none());
assert!(tree2.minimum().is_none());
tree2.insert(0);
assert_eq!(*tree2.minimum().unwrap(), 0);
assert_eq!(*tree2.maximum().unwrap(), 0);
tree2.insert(-5);
assert_eq!(*tree2.minimum().unwrap(), -5);
assert_eq!(*tree2.maximum().unwrap(), 0);
tree2.insert(5);
assert_eq!(*tree2.minimum().unwrap(), -5);
assert_eq!(*tree2.maximum().unwrap(), 5);
}
#[test]
fn test_floor_and_ceil() {
let tree = prequel_memes_tree();
assert_eq!(*tree.floor(&"hello there").unwrap(), "hello there");
assert_eq!(
*tree
.floor(&"these are not the droids you're looking for")
.unwrap(),
"kill him"
);
assert!(tree.floor(&"another death star").is_none());
assert_eq!(*tree.floor(&"you fool").unwrap(), "you fool");
assert_eq!(
*tree.floor(&"but i was going to tasche station").unwrap(),
"back away...I will deal with this jedi slime myself"
);
assert_eq!(
*tree.floor(&"you underestimate my power").unwrap(),
"you fool"
);
assert_eq!(*tree.floor(&"your new empire").unwrap(), "your move");
assert_eq!(*tree.ceil(&"hello there").unwrap(), "hello there");
assert_eq!(
*tree
.ceil(&"these are not the droids you're looking for")
.unwrap(),
"you are a bold one"
);
assert_eq!(
*tree.ceil(&"another death star").unwrap(),
"back away...I will deal with this jedi slime myself"
);
assert_eq!(*tree.ceil(&"you fool").unwrap(), "you fool");
assert_eq!(
*tree.ceil(&"but i was going to tasche station").unwrap(),
"general kenobi"
);
assert_eq!(
*tree.ceil(&"you underestimate my power").unwrap(),
"your move"
);
assert!(tree.ceil(&"your new empire").is_none());
}
#[test]
fn test_iterator() {
let tree = prequel_memes_tree();
let mut iter = tree.iter();
assert_eq!(
iter.next().unwrap(),
&"back away...I will deal with this jedi slime myself"
);
assert_eq!(iter.next().unwrap(), &"general kenobi");
assert_eq!(iter.next().unwrap(), &"hello there");
assert_eq!(iter.next().unwrap(), &"kill him");
assert_eq!(iter.next().unwrap(), &"you are a bold one");
assert_eq!(iter.next().unwrap(), &"you fool");
assert_eq!(iter.next().unwrap(), &"your move");
assert_eq!(iter.next(), None);
assert_eq!(iter.next(), None);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/range_minimum_query.rs | src/data_structures/range_minimum_query.rs | //! Range Minimum Query (RMQ) Implementation
//!
//! This module provides an efficient implementation of a Range Minimum Query data structure using a
//! sparse table approach. It allows for quick retrieval of the minimum value within a specified subdata
//! of a given data after an initial preprocessing phase.
//!
//! The RMQ is particularly useful in scenarios requiring multiple queries on static data, as it
//! allows querying in constant time after an O(n log(n)) preprocessing time.
//!
//! References: [Wikipedia](https://en.wikipedia.org/wiki/Range_minimum_query)
use std::cmp::PartialOrd;
/// Custom error type for invalid range queries.
#[derive(Debug, PartialEq, Eq)]
pub enum RangeError {
/// Indicates that the provided range is invalid (start index is not less than end index).
InvalidRange,
/// Indicates that one or more indices are out of bounds for the data.
IndexOutOfBound,
}
/// A data structure for efficiently answering range minimum queries on static data.
pub struct RangeMinimumQuery<T: PartialOrd + Copy> {
/// The original input data on which range queries are performed.
data: Vec<T>,
/// The sparse table for storing preprocessed range minimum information. Each entry
/// contains the index of the minimum element in the range starting at `j` and having a length of `2^i`.
sparse_table: Vec<Vec<usize>>,
}
impl<T: PartialOrd + Copy> RangeMinimumQuery<T> {
/// Creates a new `RangeMinimumQuery` instance with the provided input data.
///
/// # Arguments
///
/// * `input` - A slice of elements of type `T` that implement `PartialOrd` and `Copy`.
///
/// # Returns
///
/// A `RangeMinimumQuery` instance that can be used to perform range minimum queries.
pub fn new(input: &[T]) -> RangeMinimumQuery<T> {
RangeMinimumQuery {
data: input.to_vec(),
sparse_table: build_sparse_table(input),
}
}
/// Retrieves the minimum value in the specified range [start, end).
///
/// # Arguments
///
/// * `start` - The starting index of the range (inclusive).
/// * `end` - The ending index of the range (exclusive).
///
/// # Returns
///
/// * `Ok(T)` - The minimum value found in the specified range.
/// * `Err(RangeError)` - An error indicating the reason for failure, such as an invalid range
/// or indices out of bounds.
pub fn get_range_min(&self, start: usize, end: usize) -> Result<T, RangeError> {
// Validate range
if start >= end {
return Err(RangeError::InvalidRange);
}
if start >= self.data.len() || end > self.data.len() {
return Err(RangeError::IndexOutOfBound);
}
// Calculate the log length and the index for the sparse table
let log_len = (end - start).ilog2() as usize;
let idx: usize = end - (1 << log_len);
// Retrieve the indices of the minimum values from the sparse table
let min_idx_start = self.sparse_table[log_len][start];
let min_idx_end = self.sparse_table[log_len][idx];
// Compare the values at the retrieved indices and return the minimum
if self.data[min_idx_start] < self.data[min_idx_end] {
Ok(self.data[min_idx_start])
} else {
Ok(self.data[min_idx_end])
}
}
}
/// Builds a sparse table for the provided data to support range minimum queries.
///
/// # Arguments
///
/// * `data` - A slice of elements of type `T` that implement `PartialOrd`.
///
/// # Returns
///
/// A 2D vector representing the sparse table, where each entry contains the index of the minimum
/// element in the range defined by the starting index and the power of two lengths.
fn build_sparse_table<T: PartialOrd>(data: &[T]) -> Vec<Vec<usize>> {
let mut sparse_table: Vec<Vec<usize>> = vec![(0..data.len()).collect()];
let len = data.len();
// Fill the sparse table
for log_len in 1..=len.ilog2() {
let mut row = Vec::new();
for idx in 0..=len - (1 << log_len) {
let min_idx_start = sparse_table[sparse_table.len() - 1][idx];
let min_idx_end = sparse_table[sparse_table.len() - 1][idx + (1 << (log_len - 1))];
if data[min_idx_start] < data[min_idx_end] {
row.push(min_idx_start);
} else {
row.push(min_idx_end);
}
}
sparse_table.push(row);
}
sparse_table
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_build_sparse_table {
($($name:ident: $inputs:expr,)*) => {
$(
#[test]
fn $name() {
let (data, expected) = $inputs;
assert_eq!(build_sparse_table(&data), expected);
}
)*
}
}
test_build_sparse_table! {
small: (
[1, 6, 3],
vec![
vec![0, 1, 2],
vec![0, 2]
]
),
medium: (
[1, 3, 6, 123, 7, 235, 3, -4, 6, 2],
vec![
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
vec![0, 1, 2, 4, 4, 6, 7, 7, 9],
vec![0, 1, 2, 6, 7, 7, 7],
vec![7, 7, 7]
]
),
large: (
[20, 13, -13, 2, 3634, -2, 56, 3, 67, 8, 23, 0, -23, 1, 5, 85, 3, 24, 5, -10, 3, 4, 20],
vec![
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
vec![1, 2, 2, 3, 5, 5, 7, 7, 9, 9, 11, 12, 12, 13, 14, 16, 16, 18, 19, 19, 20, 21],
vec![2, 2, 2, 5, 5, 5, 7, 7, 11, 12, 12, 12, 12, 13, 16, 16, 19, 19, 19, 19],
vec![2, 2, 2, 5, 5, 12, 12, 12, 12, 12, 12, 12, 12, 19, 19, 19],
vec![12, 12, 12, 12, 12, 12, 12, 12]
]
),
}
#[test]
fn simple_query_tests() {
let rmq = RangeMinimumQuery::new(&[1, 3, 6, 123, 7, 235, 3, -4, 6, 2]);
assert_eq!(rmq.get_range_min(1, 6), Ok(3));
assert_eq!(rmq.get_range_min(0, 10), Ok(-4));
assert_eq!(rmq.get_range_min(8, 9), Ok(6));
assert_eq!(rmq.get_range_min(4, 3), Err(RangeError::InvalidRange));
assert_eq!(rmq.get_range_min(0, 1000), Err(RangeError::IndexOutOfBound));
assert_eq!(
rmq.get_range_min(1000, 1001),
Err(RangeError::IndexOutOfBound)
);
}
#[test]
fn float_query_tests() {
let rmq = RangeMinimumQuery::new(&[0.4, -2.3, 0.0, 234.22, 12.2, -3.0]);
assert_eq!(rmq.get_range_min(0, 6), Ok(-3.0));
assert_eq!(rmq.get_range_min(0, 4), Ok(-2.3));
assert_eq!(rmq.get_range_min(3, 5), Ok(12.2));
assert_eq!(rmq.get_range_min(2, 3), Ok(0.0));
assert_eq!(rmq.get_range_min(4, 3), Err(RangeError::InvalidRange));
assert_eq!(rmq.get_range_min(0, 1000), Err(RangeError::IndexOutOfBound));
assert_eq!(
rmq.get_range_min(1000, 1001),
Err(RangeError::IndexOutOfBound)
);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/mod.rs | src/data_structures/mod.rs | mod avl_tree;
mod b_tree;
mod binary_search_tree;
mod fenwick_tree;
mod floyds_algorithm;
pub mod graph;
mod hash_table;
mod heap;
mod lazy_segment_tree;
mod linked_list;
mod probabilistic;
mod queue;
mod range_minimum_query;
mod rb_tree;
mod segment_tree;
mod segment_tree_recursive;
mod skip_list;
mod stack_using_singly_linked_list;
mod treap;
mod trie;
mod union_find;
mod veb_tree;
pub use self::avl_tree::AVLTree;
pub use self::b_tree::BTree;
pub use self::binary_search_tree::BinarySearchTree;
pub use self::fenwick_tree::FenwickTree;
pub use self::floyds_algorithm::{detect_cycle, has_cycle};
pub use self::graph::DirectedGraph;
pub use self::graph::UndirectedGraph;
pub use self::hash_table::HashTable;
pub use self::heap::Heap;
pub use self::lazy_segment_tree::LazySegmentTree;
pub use self::linked_list::LinkedList;
pub use self::probabilistic::bloom_filter;
pub use self::probabilistic::count_min_sketch;
pub use self::queue::Queue;
pub use self::range_minimum_query::RangeMinimumQuery;
pub use self::rb_tree::RBTree;
pub use self::segment_tree::SegmentTree;
pub use self::segment_tree_recursive::SegmentTree as SegmentTreeRecursive;
pub use self::skip_list::SkipList;
pub use self::stack_using_singly_linked_list::Stack;
pub use self::treap::Treap;
pub use self::trie::Trie;
pub use self::union_find::UnionFind;
pub use self::veb_tree::VebTree;
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/rb_tree.rs | src/data_structures/rb_tree.rs | use std::boxed::Box;
use std::cmp::{Ord, Ordering};
use std::iter::Iterator;
use std::ptr::null_mut;
#[derive(Copy, Clone)]
enum Color {
Red,
Black,
}
pub struct RBNode<K: Ord, V> {
key: K,
value: V,
color: Color,
parent: *mut RBNode<K, V>,
left: *mut RBNode<K, V>,
right: *mut RBNode<K, V>,
}
impl<K: Ord, V> RBNode<K, V> {
fn new(key: K, value: V) -> RBNode<K, V> {
RBNode {
key,
value,
color: Color::Red,
parent: null_mut(),
left: null_mut(),
right: null_mut(),
}
}
}
pub struct RBTree<K: Ord, V> {
root: *mut RBNode<K, V>,
}
impl<K: Ord, V> Default for RBTree<K, V> {
fn default() -> Self {
Self::new()
}
}
impl<K: Ord, V> RBTree<K, V> {
pub fn new() -> RBTree<K, V> {
RBTree::<K, V> { root: null_mut() }
}
pub fn find(&self, key: &K) -> Option<&V> {
unsafe {
let mut node = self.root;
while !node.is_null() {
node = match (*node).key.cmp(key) {
Ordering::Less => (*node).right,
Ordering::Equal => return Some(&(*node).value),
Ordering::Greater => (*node).left,
}
}
}
None
}
pub fn insert(&mut self, key: K, value: V) {
unsafe {
let mut parent = null_mut();
let mut node = self.root;
while !node.is_null() {
parent = node;
node = match (*node).key.cmp(&key) {
Ordering::Less => (*node).right,
Ordering::Equal => {
(*node).value = value;
return;
}
Ordering::Greater => (*node).left,
}
}
node = Box::into_raw(Box::new(RBNode::new(key, value)));
if parent.is_null() {
self.root = node;
} else if (*node).key < (*parent).key {
(*parent).left = node;
} else {
(*parent).right = node;
}
(*node).parent = parent;
insert_fixup(self, node);
}
}
pub fn delete(&mut self, key: &K) {
unsafe {
let mut parent = null_mut();
let mut node = self.root;
while !node.is_null() {
node = match (*node).key.cmp(key) {
Ordering::Less => {
parent = node;
(*node).right
}
Ordering::Equal => break,
Ordering::Greater => {
parent = node;
(*node).left
}
};
}
if node.is_null() {
return;
}
/* cl and cr denote left and right child of node, respectively. */
let cl = (*node).left;
let cr = (*node).right;
let mut deleted_color;
if cl.is_null() {
replace_node(self, parent, node, cr);
if cr.is_null() {
/*
* Case 1 - cl and cr are both NULL
* (n could be either color here)
*
* (n) NULL
* / \ -->
* NULL NULL
*/
deleted_color = (*node).color;
} else {
/*
* Case 2 - cl is NULL and cr is not NULL
*
* N Cr
* / \ --> / \
* NULL cr NULL NULL
*/
(*cr).parent = parent;
(*cr).color = Color::Black;
deleted_color = Color::Red;
}
} else if cr.is_null() {
/*
* Case 3 - cl is not NULL and cr is NULL
*
* N Cl
* / \ --> / \
* cl NULL NULL NULL
*/
replace_node(self, parent, node, cl);
(*cl).parent = parent;
(*cl).color = Color::Black;
deleted_color = Color::Red;
} else {
let mut victim = (*node).right;
while !(*victim).left.is_null() {
victim = (*victim).left;
}
if victim == (*node).right {
/* Case 4 - victim is the right child of node
*
* N N n
* / \ / \ / \
* (cl) cr (cl) Cr Cl Cr
*
* N n
* / \ / \
* (cl) Cr Cl Cr
* \ \
* crr crr
*/
replace_node(self, parent, node, victim);
(*victim).parent = parent;
deleted_color = (*victim).color;
(*victim).color = (*node).color;
(*victim).left = cl;
(*cl).parent = victim;
if (*victim).right.is_null() {
parent = victim;
} else {
deleted_color = Color::Red;
(*(*victim).right).color = Color::Black;
}
} else {
/*
* Case 5 - victim is not the right child of node
*/
/* vp and vr denote parent and right child of victim, respectively. */
let vp = (*victim).parent;
let vr = (*victim).right;
(*vp).left = vr;
if vr.is_null() {
deleted_color = (*victim).color;
} else {
deleted_color = Color::Red;
(*vr).parent = vp;
(*vr).color = Color::Black;
}
replace_node(self, parent, node, victim);
(*victim).parent = parent;
(*victim).color = (*node).color;
(*victim).left = cl;
(*victim).right = cr;
(*cl).parent = victim;
(*cr).parent = victim;
parent = vp;
}
}
/* release resource */
drop(Box::from_raw(node));
if matches!(deleted_color, Color::Black) {
delete_fixup(self, parent);
}
}
}
pub fn iter<'a>(&self) -> RBTreeIterator<'a, K, V> {
let mut iterator = RBTreeIterator { stack: Vec::new() };
let mut node = self.root;
unsafe {
while !node.is_null() {
iterator.stack.push(&*node);
node = (*node).left;
}
}
iterator
}
}
#[inline]
unsafe fn insert_fixup<K: Ord, V>(tree: &mut RBTree<K, V>, mut node: *mut RBNode<K, V>) {
let mut parent: *mut RBNode<K, V> = (*node).parent;
let mut gparent: *mut RBNode<K, V>;
let mut tmp: *mut RBNode<K, V>;
loop {
/*
* Loop invariant:
* - node is red
*/
if parent.is_null() {
(*node).color = Color::Black;
break;
}
if matches!((*parent).color, Color::Black) {
break;
}
gparent = (*parent).parent;
tmp = (*gparent).right;
if parent == tmp {
/* parent = (*gparent).right */
tmp = (*gparent).left;
if !tmp.is_null() && matches!((*tmp).color, Color::Red) {
/*
* Case 1 - color flips and recurse at g
* G g
* / \ / \
* u p --> U P
* \ \
* n n
*/
(*parent).color = Color::Black;
(*tmp).color = Color::Black;
(*gparent).color = Color::Red;
node = gparent;
parent = (*node).parent;
continue;
}
tmp = (*parent).left;
if node == tmp {
/*
* Case 2 - right rotate at p (then Case 3)
*
* G G
* / \ / \
* U p --> U n
* / \
* n p
*/
right_rotate(tree, parent);
parent = node;
}
/*
* Case 3 - left rotate at g
*
* G P
* / \ / \
* U p --> g n
* \ /
* n U
*/
(*parent).color = Color::Black;
(*gparent).color = Color::Red;
left_rotate(tree, gparent);
} else {
/* parent = (*gparent).left */
if !tmp.is_null() && matches!((*tmp).color, Color::Red) {
/*
* Case 1 - color flips and recurse at g
*
* G g
* / \ / \
* p u --> P U
* / /
* n n
*/
(*parent).color = Color::Black;
(*tmp).color = Color::Black;
(*gparent).color = Color::Red;
node = gparent;
parent = (*node).parent;
continue;
}
tmp = (*parent).right;
if node == tmp {
/* node = (*parent).right */
/*
* Case 2 - left rotate at p (then Case 3)
*
* G G
* / \ / \
* p U --> n U
* \ /
* n p
*/
left_rotate(tree, parent);
parent = node;
}
/*
* Case 3 - right rotate at g
*
* G P
* / \ / \
* p U --> n g
* / \
* n U
*/
(*parent).color = Color::Black;
(*gparent).color = Color::Red;
right_rotate(tree, gparent);
}
break;
}
}
#[inline]
unsafe fn delete_fixup<K: Ord, V>(tree: &mut RBTree<K, V>, mut parent: *mut RBNode<K, V>) {
let mut node: *mut RBNode<K, V> = null_mut();
let mut sibling: *mut RBNode<K, V>;
/* sl and sr denote left and right child of sibling, respectively. */
let mut sl: *mut RBNode<K, V>;
let mut sr: *mut RBNode<K, V>;
loop {
// rb-tree will keep color balance up to root,
// if parent is null, we are done.
if parent.is_null() {
break;
}
/*
* Loop invariants:
* - node is black (or null on first iteration)
* - node is not the root (so parent is not null)
* - All leaf paths going through parent and node have a
* black node count that is 1 lower than other leaf paths.
*/
sibling = (*parent).right;
if node == sibling {
/* node = (*parent).right */
sibling = (*parent).left;
if matches!((*sibling).color, Color::Red) {
/*
* Case 1 - right rotate at parent
*/
right_rotate(tree, parent);
(*parent).color = Color::Red;
(*sibling).color = Color::Black;
sibling = (*parent).right;
}
sl = (*sibling).left;
sr = (*sibling).right;
if !sr.is_null() && matches!((*sr).color, Color::Red) {
/*
* Case 2 - left rotate at sibling and then right rotate at parent
*/
(*sr).color = (*parent).color;
(*parent).color = Color::Black;
left_rotate(tree, sibling);
right_rotate(tree, parent);
} else if !sl.is_null() && matches!((*sl).color, Color::Red) {
/*
* Case 3 - right rotate at parent
*/
(*sl).color = (*parent).color;
right_rotate(tree, parent);
} else {
/*
* Case 4 - color flip
*/
(*sibling).color = Color::Red;
if matches!((*parent).color, Color::Black) {
node = parent;
parent = (*node).parent;
continue;
}
(*parent).color = Color::Black;
}
} else {
/* node = (*parent).left */
if matches!((*sibling).color, Color::Red) {
/*
* Case 1 - left rotate at parent
*
* P S
* / \ / \
* N s --> p Sr
* / \ / \
* Sl Sr N Sl
*/
left_rotate(tree, parent);
(*parent).color = Color::Red;
(*sibling).color = Color::Black;
sibling = (*parent).right;
}
sl = (*sibling).left;
sr = (*sibling).right;
if !sl.is_null() && matches!((*sl).color, Color::Red) {
/*
* Case 2 - right rotate at sibling and then left rotate at parent
* (p and sr could be either color here)
*
* (p) (p) (sl)
* / \ / \ / \
* N S --> N sl --> P S
* / \ \ / \
* sl (sr) S N (sr)
* \
* (sr)
*/
(*sl).color = (*parent).color;
(*parent).color = Color::Black;
right_rotate(tree, sibling);
left_rotate(tree, parent);
} else if !sr.is_null() && matches!((*sr).color, Color::Red) {
/*
* Case 3 - left rotate at parent
* (p could be either color here)
*
* (p) S
* / \ / \
* N S --> (p) (sr)
* / \ / \
* Sl sr N Sl
*/
(*sr).color = (*parent).color;
left_rotate(tree, parent);
} else {
/*
* Case 4 - color clip
* (p could be either color here)
*
* (p) (p)
* / \ / \
* N S --> N s
* / \ / \
* Sl Sr Sl Sr
*/
(*sibling).color = Color::Red;
if matches!((*parent).color, Color::Black) {
node = parent;
parent = (*node).parent;
continue;
}
(*parent).color = Color::Black;
}
}
break;
}
}
#[inline]
unsafe fn left_rotate<K: Ord, V>(tree: &mut RBTree<K, V>, x: *mut RBNode<K, V>) {
/*
* Left rotate at x
* (x could also be the left child of p)
*
* p p
* \ \
* x --> y
* / \ / \
* y x
* / \ / \
* c c
*/
let p = (*x).parent;
let y = (*x).right;
let c = (*y).left;
(*y).left = x;
(*x).parent = y;
(*x).right = c;
if !c.is_null() {
(*c).parent = x;
}
if p.is_null() {
tree.root = y;
} else if (*p).left == x {
(*p).left = y;
} else {
(*p).right = y;
}
(*y).parent = p;
}
#[inline]
unsafe fn right_rotate<K: Ord, V>(tree: &mut RBTree<K, V>, x: *mut RBNode<K, V>) {
/*
* Right rotate at x
* (x could also be the left child of p)
*
* p p
* \ \
* x --> y
* / \ / \
* y x
* / \ / \
* c c
*/
let p = (*x).parent;
let y = (*x).left;
let c = (*y).right;
(*y).right = x;
(*x).parent = y;
(*x).left = c;
if !c.is_null() {
(*c).parent = x;
}
if p.is_null() {
tree.root = y;
} else if (*p).left == x {
(*p).left = y;
} else {
(*p).right = y;
}
(*y).parent = p;
}
#[inline]
unsafe fn replace_node<K: Ord, V>(
tree: &mut RBTree<K, V>,
parent: *mut RBNode<K, V>,
node: *mut RBNode<K, V>,
new: *mut RBNode<K, V>,
) {
if parent.is_null() {
tree.root = new;
} else if (*parent).left == node {
(*parent).left = new;
} else {
(*parent).right = new;
}
}
pub struct RBTreeIterator<'a, K: Ord, V> {
stack: Vec<&'a RBNode<K, V>>,
}
impl<'a, K: Ord, V> Iterator for RBTreeIterator<'a, K, V> {
type Item = &'a RBNode<K, V>;
fn next(&mut self) -> Option<Self::Item> {
match self.stack.pop() {
Some(node) => {
let mut next = node.right;
unsafe {
while !next.is_null() {
self.stack.push(&*next);
next = (*next).left;
}
}
Some(node)
}
None => None,
}
}
}
#[cfg(test)]
mod tests {
use super::RBTree;
#[test]
fn find() {
let mut tree = RBTree::<usize, char>::new();
for (k, v) in "hello, world!".chars().enumerate() {
tree.insert(k, v);
}
assert_eq!(*tree.find(&3).unwrap_or(&'*'), 'l');
assert_eq!(*tree.find(&6).unwrap_or(&'*'), ' ');
assert_eq!(*tree.find(&8).unwrap_or(&'*'), 'o');
assert_eq!(*tree.find(&12).unwrap_or(&'*'), '!');
}
#[test]
fn insert() {
let mut tree = RBTree::<usize, char>::new();
for (k, v) in "hello, world!".chars().enumerate() {
tree.insert(k, v);
}
let s: String = tree.iter().map(|x| x.value).collect();
assert_eq!(s, "hello, world!");
}
#[test]
fn delete() {
let mut tree = RBTree::<usize, char>::new();
for (k, v) in "hello, world!".chars().enumerate() {
tree.insert(k, v);
}
tree.delete(&1);
tree.delete(&3);
tree.delete(&5);
tree.delete(&7);
tree.delete(&11);
let s: String = tree.iter().map(|x| x.value).collect();
assert_eq!(s, "hlo orl!");
}
#[test]
fn delete_edge_case_null_pointer_guard() {
let mut tree = RBTree::<i8, i8>::new();
tree.insert(4, 4);
tree.insert(2, 2);
tree.insert(5, 5);
tree.insert(0, 0);
tree.insert(3, 3);
tree.insert(-1, -1);
tree.insert(1, 1);
tree.insert(-2, -2);
tree.insert(6, 6);
tree.insert(7, 7);
tree.insert(8, 8);
tree.delete(&1);
tree.delete(&3);
tree.delete(&-1);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/linked_list.rs | src/data_structures/linked_list.rs | use std::fmt::{self, Display, Formatter};
use std::marker::PhantomData;
use std::ptr::NonNull;
pub struct Node<T> {
pub val: T,
pub next: Option<NonNull<Node<T>>>,
prev: Option<NonNull<Node<T>>>,
}
impl<T> Node<T> {
fn new(t: T) -> Node<T> {
Node {
val: t,
prev: None,
next: None,
}
}
}
pub struct LinkedList<T> {
pub length: u32,
pub head: Option<NonNull<Node<T>>>,
pub tail: Option<NonNull<Node<T>>>,
// Act like we own boxed nodes since we construct and leak them
marker: PhantomData<Box<Node<T>>>,
}
impl<T> Default for LinkedList<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> LinkedList<T> {
pub fn new() -> Self {
Self {
length: 0,
head: None,
tail: None,
marker: PhantomData,
}
}
pub fn insert_at_head(&mut self, obj: T) {
let mut node = Box::new(Node::new(obj));
node.next = self.head;
node.prev = None;
let node_ptr = NonNull::new(Box::into_raw(node));
match self.head {
None => self.tail = node_ptr,
Some(head_ptr) => unsafe { (*head_ptr.as_ptr()).prev = node_ptr },
}
self.head = node_ptr;
self.length += 1;
}
pub fn insert_at_tail(&mut self, obj: T) {
let mut node = Box::new(Node::new(obj));
node.next = None;
node.prev = self.tail;
let node_ptr = NonNull::new(Box::into_raw(node));
match self.tail {
None => self.head = node_ptr,
Some(tail_ptr) => unsafe { (*tail_ptr.as_ptr()).next = node_ptr },
}
self.tail = node_ptr;
self.length += 1;
}
pub fn insert_at_ith(&mut self, index: u32, obj: T) {
if self.length < index {
panic!("Index out of bounds");
}
if index == 0 || self.head.is_none() {
self.insert_at_head(obj);
return;
}
if self.length == index {
self.insert_at_tail(obj);
return;
}
if let Some(mut ith_node) = self.head {
for _ in 0..index {
unsafe {
match (*ith_node.as_ptr()).next {
None => panic!("Index out of bounds"),
Some(next_ptr) => ith_node = next_ptr,
}
}
}
let mut node = Box::new(Node::new(obj));
unsafe {
node.prev = (*ith_node.as_ptr()).prev;
node.next = Some(ith_node);
if let Some(p) = (*ith_node.as_ptr()).prev {
let node_ptr = NonNull::new(Box::into_raw(node));
println!("{:?}", (*p.as_ptr()).next);
(*p.as_ptr()).next = node_ptr;
(*ith_node.as_ptr()).prev = node_ptr;
self.length += 1;
}
}
}
}
pub fn delete_head(&mut self) -> Option<T> {
// Safety: head_ptr points to a leaked boxed node managed by this list
// We reassign pointers that pointed to the head node
if self.length == 0 {
return None;
}
self.head.map(|head_ptr| unsafe {
let old_head = Box::from_raw(head_ptr.as_ptr());
match old_head.next {
Some(mut next_ptr) => next_ptr.as_mut().prev = None,
None => self.tail = None,
}
self.head = old_head.next;
self.length = self.length.checked_add_signed(-1).unwrap_or(0);
old_head.val
})
// None
}
pub fn delete_tail(&mut self) -> Option<T> {
// Safety: tail_ptr points to a leaked boxed node managed by this list
// We reassign pointers that pointed to the tail node
self.tail.map(|tail_ptr| unsafe {
let old_tail = Box::from_raw(tail_ptr.as_ptr());
match old_tail.prev {
Some(mut prev) => prev.as_mut().next = None,
None => self.head = None,
}
self.tail = old_tail.prev;
self.length -= 1;
old_tail.val
})
}
pub fn delete_ith(&mut self, index: u32) -> Option<T> {
if self.length <= index {
panic!("Index out of bounds");
}
if index == 0 || self.head.is_none() {
return self.delete_head();
}
if self.length - 1 == index {
return self.delete_tail();
}
if let Some(mut ith_node) = self.head {
for _ in 0..index {
unsafe {
match (*ith_node.as_ptr()).next {
None => panic!("Index out of bounds"),
Some(next_ptr) => ith_node = next_ptr,
}
}
}
unsafe {
let old_ith = Box::from_raw(ith_node.as_ptr());
if let Some(mut prev) = old_ith.prev {
prev.as_mut().next = old_ith.next;
}
if let Some(mut next) = old_ith.next {
next.as_mut().prev = old_ith.prev;
}
self.length -= 1;
Some(old_ith.val)
}
} else {
None
}
}
pub fn get(&self, index: i32) -> Option<&T> {
Self::get_ith_node(self.head, index).map(|ptr| unsafe { &(*ptr.as_ptr()).val })
}
fn get_ith_node(node: Option<NonNull<Node<T>>>, index: i32) -> Option<NonNull<Node<T>>> {
match node {
None => None,
Some(next_ptr) => match index {
0 => Some(next_ptr),
_ => Self::get_ith_node(unsafe { (*next_ptr.as_ptr()).next }, index - 1),
},
}
}
}
impl<T> Drop for LinkedList<T> {
fn drop(&mut self) {
// Pop items until there are none left
while self.delete_head().is_some() {}
}
}
impl<T> Display for LinkedList<T>
where
T: Display,
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.head {
Some(node) => write!(f, "{}", unsafe { node.as_ref() }),
None => Ok(()),
}
}
}
impl<T> Display for Node<T>
where
T: Display,
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.next {
Some(node) => write!(f, "{}, {}", self.val, unsafe { node.as_ref() }),
None => write!(f, "{}", self.val),
}
}
}
#[cfg(test)]
mod tests {
use std::convert::TryInto;
use super::LinkedList;
#[test]
fn insert_at_tail_works() {
let mut list = LinkedList::<i32>::new();
let second_value = 2;
list.insert_at_tail(1);
list.insert_at_tail(second_value);
println!("Linked List is {list}");
match list.get(1) {
Some(val) => assert_eq!(*val, second_value),
None => panic!("Expected to find {second_value} at index 1"),
}
}
#[test]
fn insert_at_head_works() {
let mut list = LinkedList::<i32>::new();
let second_value = 2;
list.insert_at_head(1);
list.insert_at_head(second_value);
println!("Linked List is {list}");
match list.get(0) {
Some(val) => assert_eq!(*val, second_value),
None => panic!("Expected to find {second_value} at index 0"),
}
}
#[test]
fn insert_at_ith_can_add_to_tail() {
let mut list = LinkedList::<i32>::new();
let second_value = 2;
list.insert_at_ith(0, 0);
list.insert_at_ith(1, second_value);
println!("Linked List is {list}");
match list.get(1) {
Some(val) => assert_eq!(*val, second_value),
None => panic!("Expected to find {second_value} at index 1"),
}
}
#[test]
fn insert_at_ith_can_add_to_head() {
let mut list = LinkedList::<i32>::new();
let second_value = 2;
list.insert_at_ith(0, 1);
list.insert_at_ith(0, second_value);
println!("Linked List is {list}");
match list.get(0) {
Some(val) => assert_eq!(*val, second_value),
None => panic!("Expected to find {second_value} at index 0"),
}
}
#[test]
fn insert_at_ith_can_add_to_middle() {
let mut list = LinkedList::<i32>::new();
let second_value = 2;
let third_value = 3;
list.insert_at_ith(0, 1);
list.insert_at_ith(1, second_value);
list.insert_at_ith(1, third_value);
println!("Linked List is {list}");
match list.get(1) {
Some(val) => assert_eq!(*val, third_value),
None => panic!("Expected to find {third_value} at index 1"),
}
match list.get(2) {
Some(val) => assert_eq!(*val, second_value),
None => panic!("Expected to find {second_value} at index 1"),
}
}
#[test]
fn insert_at_ith_and_delete_at_ith_in_the_middle() {
// Insert and delete in the middle of the list to ensure pointers are updated correctly
let mut list = LinkedList::<i32>::new();
let first_value = 0;
let second_value = 1;
let third_value = 2;
let fourth_value = 3;
list.insert_at_ith(0, first_value);
list.insert_at_ith(1, fourth_value);
list.insert_at_ith(1, third_value);
list.insert_at_ith(1, second_value);
list.delete_ith(2);
list.insert_at_ith(2, third_value);
for (i, expected) in [
(0, first_value),
(1, second_value),
(2, third_value),
(3, fourth_value),
] {
match list.get(i) {
Some(val) => assert_eq!(*val, expected),
None => panic!("Expected to find {expected} at index {i}"),
}
}
}
#[test]
fn insert_at_ith_and_delete_ith_work_over_many_iterations() {
let mut list = LinkedList::<i32>::new();
for i in 0..100 {
list.insert_at_ith(i, i.try_into().unwrap());
}
// Pop even numbers to 50
for i in 0..50 {
println!("list.length {}", list.length);
if i % 2 == 0 {
list.delete_ith(i);
}
}
assert_eq!(list.length, 75);
// Insert even numbers back
for i in 0..50 {
if i % 2 == 0 {
list.insert_at_ith(i, i.try_into().unwrap());
}
}
assert_eq!(list.length, 100);
// Ensure numbers were adderd back and we're able to traverse nodes
if let Some(val) = list.get(78) {
assert_eq!(*val, 78);
} else {
panic!("Expected to find 78 at index 78");
}
}
#[test]
fn delete_tail_works() {
let mut list = LinkedList::<i32>::new();
let first_value = 1;
let second_value = 2;
list.insert_at_tail(first_value);
list.insert_at_tail(second_value);
match list.delete_tail() {
Some(val) => assert_eq!(val, 2),
None => panic!("Expected to remove {second_value} at tail"),
}
println!("Linked List is {list}");
match list.get(0) {
Some(val) => assert_eq!(*val, first_value),
None => panic!("Expected to find {first_value} at index 0"),
}
}
#[test]
fn delete_head_works() {
let mut list = LinkedList::<i32>::new();
let first_value = 1;
let second_value = 2;
list.insert_at_tail(first_value);
list.insert_at_tail(second_value);
match list.delete_head() {
Some(val) => assert_eq!(val, 1),
None => panic!("Expected to remove {first_value} at head"),
}
println!("Linked List is {list}");
match list.get(0) {
Some(val) => assert_eq!(*val, second_value),
None => panic!("Expected to find {second_value} at index 0"),
}
}
#[test]
fn delete_ith_can_delete_at_tail() {
let mut list = LinkedList::<i32>::new();
let first_value = 1;
let second_value = 2;
list.insert_at_tail(first_value);
list.insert_at_tail(second_value);
match list.delete_ith(1) {
Some(val) => assert_eq!(val, 2),
None => panic!("Expected to remove {second_value} at tail"),
}
assert_eq!(list.length, 1);
}
#[test]
fn delete_ith_can_delete_at_head() {
let mut list = LinkedList::<i32>::new();
let first_value = 1;
let second_value = 2;
list.insert_at_tail(first_value);
list.insert_at_tail(second_value);
match list.delete_ith(0) {
Some(val) => assert_eq!(val, 1),
None => panic!("Expected to remove {first_value} at tail"),
}
assert_eq!(list.length, 1);
}
#[test]
fn delete_ith_can_delete_in_middle() {
let mut list = LinkedList::<i32>::new();
let first_value = 1;
let second_value = 2;
let third_value = 3;
list.insert_at_tail(first_value);
list.insert_at_tail(second_value);
list.insert_at_tail(third_value);
match list.delete_ith(1) {
Some(val) => assert_eq!(val, 2),
None => panic!("Expected to remove {second_value} at tail"),
}
match list.get(1) {
Some(val) => assert_eq!(*val, third_value),
None => panic!("Expected to find {third_value} at index 1"),
}
}
#[test]
fn create_numeric_list() {
let mut list = LinkedList::<i32>::new();
list.insert_at_tail(1);
list.insert_at_tail(2);
list.insert_at_tail(3);
println!("Linked List is {list}");
assert_eq!(3, list.length);
}
#[test]
fn create_string_list() {
let mut list_str = LinkedList::<String>::new();
list_str.insert_at_tail("A".to_string());
list_str.insert_at_tail("B".to_string());
list_str.insert_at_tail("C".to_string());
println!("Linked List is {list_str}");
assert_eq!(3, list_str.length);
}
#[test]
fn get_by_index_in_numeric_list() {
let mut list = LinkedList::<i32>::new();
list.insert_at_tail(1);
list.insert_at_tail(2);
println!("Linked List is {list}");
let retrived_item = list.get(1);
assert!(retrived_item.is_some());
assert_eq!(2, *retrived_item.unwrap());
}
#[test]
fn get_by_index_in_string_list() {
let mut list_str = LinkedList::<String>::new();
list_str.insert_at_tail("A".to_string());
list_str.insert_at_tail("B".to_string());
println!("Linked List is {list_str}");
let retrived_item = list_str.get(1);
assert!(retrived_item.is_some());
assert_eq!("B", *retrived_item.unwrap());
}
#[test]
#[should_panic(expected = "Index out of bounds")]
fn delete_ith_panics_if_index_equals_length() {
let mut list = LinkedList::<i32>::new();
list.insert_at_tail(1);
list.insert_at_tail(2);
// length is 2, so index 2 is out of bounds
list.delete_ith(2);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/hash_table.rs | src/data_structures/hash_table.rs | use std::collections::LinkedList;
pub struct HashTable<K, V> {
elements: Vec<LinkedList<(K, V)>>,
count: usize,
}
impl<K: Hashable + std::cmp::PartialEq, V> Default for HashTable<K, V> {
fn default() -> Self {
Self::new()
}
}
pub trait Hashable {
fn hash(&self) -> usize;
}
impl<K: Hashable + std::cmp::PartialEq, V> HashTable<K, V> {
pub fn new() -> HashTable<K, V> {
let initial_capacity = 3000;
let mut elements = Vec::with_capacity(initial_capacity);
for _ in 0..initial_capacity {
elements.push(LinkedList::new());
}
HashTable { elements, count: 0 }
}
pub fn insert(&mut self, key: K, value: V) {
if self.count >= self.elements.len() * 3 / 4 {
self.resize();
}
let index = key.hash() % self.elements.len();
self.elements[index].push_back((key, value));
self.count += 1;
}
pub fn search(&self, key: K) -> Option<&V> {
let index = key.hash() % self.elements.len();
self.elements[index]
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| v)
}
fn resize(&mut self) {
let new_size = self.elements.len() * 2;
let mut new_elements = Vec::with_capacity(new_size);
for _ in 0..new_size {
new_elements.push(LinkedList::new());
}
for old_list in self.elements.drain(..) {
for (key, value) in old_list {
let new_index = key.hash() % new_size;
new_elements[new_index].push_back((key, value));
}
}
self.elements = new_elements;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, PartialEq, Eq)]
struct TestKey(usize);
impl Hashable for TestKey {
fn hash(&self) -> usize {
self.0
}
}
#[test]
fn test_insert_and_search() {
let mut hash_table = HashTable::new();
let key = TestKey(1);
let value = TestKey(10);
hash_table.insert(key, value);
let result = hash_table.search(TestKey(1));
assert_eq!(result, Some(&TestKey(10)));
}
#[test]
fn test_resize() {
let mut hash_table = HashTable::new();
let initial_capacity = hash_table.elements.capacity();
for i in 0..=initial_capacity * 3 / 4 {
hash_table.insert(TestKey(i), TestKey(i + 10));
}
assert!(hash_table.elements.capacity() > initial_capacity);
}
#[test]
fn test_search_nonexistent() {
let mut hash_table = HashTable::new();
let key = TestKey(1);
let value = TestKey(10);
hash_table.insert(key, value);
let result = hash_table.search(TestKey(2));
assert_eq!(result, None);
}
#[test]
fn test_multiple_inserts_and_searches() {
let mut hash_table = HashTable::new();
for i in 0..10 {
hash_table.insert(TestKey(i), TestKey(i + 100));
}
for i in 0..10 {
let result = hash_table.search(TestKey(i));
assert_eq!(result, Some(&TestKey(i + 100)));
}
}
#[test]
fn test_not_overwrite_existing_key() {
let mut hash_table = HashTable::new();
hash_table.insert(TestKey(1), TestKey(100));
hash_table.insert(TestKey(1), TestKey(200));
let result = hash_table.search(TestKey(1));
assert_eq!(result, Some(&TestKey(100)));
}
#[test]
fn test_empty_search() {
let hash_table: HashTable<TestKey, TestKey> = HashTable::new();
let result = hash_table.search(TestKey(1));
assert_eq!(result, None);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/segment_tree.rs | src/data_structures/segment_tree.rs | //! A module providing a Segment Tree data structure for efficient range queries
//! and updates. It supports operations like finding the minimum, maximum,
//! and sum of segments in an array.
use std::fmt::Debug;
use std::ops::Range;
/// Custom error types representing possible errors that can occur during operations on the `SegmentTree`.
#[derive(Debug, PartialEq, Eq)]
pub enum SegmentTreeError {
/// Error indicating that an index is out of bounds.
IndexOutOfBounds,
/// Error indicating that a range provided for a query is invalid.
InvalidRange,
}
/// A structure representing a Segment Tree. This tree can be used to efficiently
/// perform range queries and updates on an array of elements.
pub struct SegmentTree<T, F>
where
T: Debug + Default + Ord + Copy,
F: Fn(T, T) -> T,
{
/// The length of the input array for which the segment tree is built.
size: usize,
/// A vector representing the segment tree.
nodes: Vec<T>,
/// A merging function defined as a closure or callable type.
merge_fn: F,
}
impl<T, F> SegmentTree<T, F>
where
T: Debug + Default + Ord + Copy,
F: Fn(T, T) -> T,
{
/// Creates a new `SegmentTree` from the provided slice of elements.
///
/// # Arguments
///
/// * `arr`: A slice of elements of type `T` to initialize the segment tree.
/// * `merge`: A merging function that defines how to merge two elements of type `T`.
///
/// # Returns
///
/// A new `SegmentTree` instance populated with the given elements.
pub fn from_vec(arr: &[T], merge: F) -> Self {
let size = arr.len();
let mut buffer: Vec<T> = vec![T::default(); 2 * size];
// Populate the leaves of the tree
buffer[size..(2 * size)].clone_from_slice(arr);
for idx in (1..size).rev() {
buffer[idx] = merge(buffer[2 * idx], buffer[2 * idx + 1]);
}
SegmentTree {
size,
nodes: buffer,
merge_fn: merge,
}
}
/// Queries the segment tree for the result of merging the elements in the given range.
///
/// # Arguments
///
/// * `range`: A range specified as `Range<usize>`, indicating the start (inclusive)
/// and end (exclusive) indices of the segment to query.
///
/// # Returns
///
/// * `Ok(Some(result))` if the query was successful and there are elements in the range,
/// * `Ok(None)` if the range is empty,
/// * `Err(SegmentTreeError::InvalidRange)` if the provided range is invalid.
pub fn query(&self, range: Range<usize>) -> Result<Option<T>, SegmentTreeError> {
if range.start >= self.size || range.end > self.size {
return Err(SegmentTreeError::InvalidRange);
}
let mut left = range.start + self.size;
let mut right = range.end + self.size;
let mut result = None;
// Iterate through the segment tree to accumulate results
while left < right {
if left % 2 == 1 {
result = Some(match result {
None => self.nodes[left],
Some(old) => (self.merge_fn)(old, self.nodes[left]),
});
left += 1;
}
if right % 2 == 1 {
right -= 1;
result = Some(match result {
None => self.nodes[right],
Some(old) => (self.merge_fn)(old, self.nodes[right]),
});
}
left /= 2;
right /= 2;
}
Ok(result)
}
/// Updates the value at the specified index in the segment tree.
///
/// # Arguments
///
/// * `idx`: The index (0-based) of the element to update.
/// * `val`: The new value of type `T` to set at the specified index.
///
/// # Returns
///
/// * `Ok(())` if the update was successful,
/// * `Err(SegmentTreeError::IndexOutOfBounds)` if the index is out of bounds.
pub fn update(&mut self, idx: usize, val: T) -> Result<(), SegmentTreeError> {
if idx >= self.size {
return Err(SegmentTreeError::IndexOutOfBounds);
}
let mut index = idx + self.size;
if self.nodes[index] == val {
return Ok(());
}
self.nodes[index] = val;
while index > 1 {
index /= 2;
self.nodes[index] = (self.merge_fn)(self.nodes[2 * index], self.nodes[2 * index + 1]);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cmp::{max, min};
#[test]
fn test_min_segments() {
let vec = vec![-30, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8];
let mut min_seg_tree = SegmentTree::from_vec(&vec, min);
assert_eq!(min_seg_tree.query(4..7), Ok(Some(-5)));
assert_eq!(min_seg_tree.query(0..vec.len()), Ok(Some(-30)));
assert_eq!(min_seg_tree.query(0..2), Ok(Some(-30)));
assert_eq!(min_seg_tree.query(1..3), Ok(Some(-4)));
assert_eq!(min_seg_tree.query(1..7), Ok(Some(-5)));
assert_eq!(min_seg_tree.update(5, 10), Ok(()));
assert_eq!(min_seg_tree.update(14, -8), Ok(()));
assert_eq!(min_seg_tree.query(4..7), Ok(Some(3)));
assert_eq!(
min_seg_tree.update(15, 100),
Err(SegmentTreeError::IndexOutOfBounds)
);
assert_eq!(min_seg_tree.query(5..5), Ok(None));
assert_eq!(
min_seg_tree.query(10..16),
Err(SegmentTreeError::InvalidRange)
);
assert_eq!(
min_seg_tree.query(15..20),
Err(SegmentTreeError::InvalidRange)
);
}
#[test]
fn test_max_segments() {
let vec = vec![1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8];
let mut max_seg_tree = SegmentTree::from_vec(&vec, max);
assert_eq!(max_seg_tree.query(0..vec.len()), Ok(Some(15)));
assert_eq!(max_seg_tree.query(3..5), Ok(Some(7)));
assert_eq!(max_seg_tree.query(4..8), Ok(Some(11)));
assert_eq!(max_seg_tree.query(8..10), Ok(Some(9)));
assert_eq!(max_seg_tree.query(9..12), Ok(Some(15)));
assert_eq!(max_seg_tree.update(4, 10), Ok(()));
assert_eq!(max_seg_tree.update(14, -8), Ok(()));
assert_eq!(max_seg_tree.query(3..5), Ok(Some(10)));
assert_eq!(
max_seg_tree.update(15, 100),
Err(SegmentTreeError::IndexOutOfBounds)
);
assert_eq!(max_seg_tree.query(5..5), Ok(None));
assert_eq!(
max_seg_tree.query(10..16),
Err(SegmentTreeError::InvalidRange)
);
assert_eq!(
max_seg_tree.query(15..20),
Err(SegmentTreeError::InvalidRange)
);
}
#[test]
fn test_sum_segments() {
let vec = vec![1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8];
let mut sum_seg_tree = SegmentTree::from_vec(&vec, |a, b| a + b);
assert_eq!(sum_seg_tree.query(0..vec.len()), Ok(Some(38)));
assert_eq!(sum_seg_tree.query(1..4), Ok(Some(5)));
assert_eq!(sum_seg_tree.query(4..7), Ok(Some(4)));
assert_eq!(sum_seg_tree.query(6..9), Ok(Some(-3)));
assert_eq!(sum_seg_tree.query(9..vec.len()), Ok(Some(37)));
assert_eq!(sum_seg_tree.update(5, 10), Ok(()));
assert_eq!(sum_seg_tree.update(14, -8), Ok(()));
assert_eq!(sum_seg_tree.query(4..7), Ok(Some(19)));
assert_eq!(
sum_seg_tree.update(15, 100),
Err(SegmentTreeError::IndexOutOfBounds)
);
assert_eq!(sum_seg_tree.query(5..5), Ok(None));
assert_eq!(
sum_seg_tree.query(10..16),
Err(SegmentTreeError::InvalidRange)
);
assert_eq!(
sum_seg_tree.query(15..20),
Err(SegmentTreeError::InvalidRange)
);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/lazy_segment_tree.rs | src/data_structures/lazy_segment_tree.rs | use std::fmt::{Debug, Display};
use std::ops::{Add, AddAssign, Range};
pub struct LazySegmentTree<T: Debug + Default + Ord + Copy + Display + AddAssign + Add<Output = T>>
{
len: usize,
tree: Vec<T>,
lazy: Vec<Option<T>>,
merge: fn(T, T) -> T,
}
impl<T: Debug + Default + Ord + Copy + Display + AddAssign + Add<Output = T>> LazySegmentTree<T> {
pub fn from_vec(arr: &[T], merge: fn(T, T) -> T) -> Self {
let len = arr.len();
let mut sgtr = LazySegmentTree {
len,
tree: vec![T::default(); 4 * len],
lazy: vec![None; 4 * len],
merge,
};
if len != 0 {
sgtr.build_recursive(arr, 1, 0..len, merge);
}
sgtr
}
fn build_recursive(
&mut self,
arr: &[T],
idx: usize,
range: Range<usize>,
merge: fn(T, T) -> T,
) {
if range.end - range.start == 1 {
self.tree[idx] = arr[range.start];
} else {
let mid = range.start + (range.end - range.start) / 2;
self.build_recursive(arr, 2 * idx, range.start..mid, merge);
self.build_recursive(arr, 2 * idx + 1, mid..range.end, merge);
self.tree[idx] = merge(self.tree[2 * idx], self.tree[2 * idx + 1]);
}
}
pub fn query(&mut self, range: Range<usize>) -> Option<T> {
self.query_recursive(1, 0..self.len, &range)
}
fn query_recursive(
&mut self,
idx: usize,
element_range: Range<usize>,
query_range: &Range<usize>,
) -> Option<T> {
if element_range.start >= query_range.end || element_range.end <= query_range.start {
return None;
}
if self.lazy[idx].is_some() {
self.propagation(idx, &element_range, T::default());
}
if element_range.start >= query_range.start && element_range.end <= query_range.end {
return Some(self.tree[idx]);
}
let mid = element_range.start + (element_range.end - element_range.start) / 2;
let left = self.query_recursive(idx * 2, element_range.start..mid, query_range);
let right = self.query_recursive(idx * 2 + 1, mid..element_range.end, query_range);
match (left, right) {
(None, None) => None,
(None, Some(r)) => Some(r),
(Some(l), None) => Some(l),
(Some(l), Some(r)) => Some((self.merge)(l, r)),
}
}
pub fn update(&mut self, target_range: Range<usize>, val: T) {
self.update_recursive(1, 0..self.len, &target_range, val);
}
fn update_recursive(
&mut self,
idx: usize,
element_range: Range<usize>,
target_range: &Range<usize>,
val: T,
) {
if element_range.start >= target_range.end || element_range.end <= target_range.start {
return;
}
if element_range.end - element_range.start == 1 {
self.tree[idx] += val;
return;
}
if element_range.start >= target_range.start && element_range.end <= target_range.end {
self.lazy[idx] = match self.lazy[idx] {
Some(lazy) => Some(lazy + val),
None => Some(val),
};
return;
}
if self.lazy[idx].is_some() && self.lazy[idx].unwrap() != T::default() {
self.propagation(idx, &element_range, T::default());
}
let mid = element_range.start + (element_range.end - element_range.start) / 2;
self.update_recursive(idx * 2, element_range.start..mid, target_range, val);
self.update_recursive(idx * 2 + 1, mid..element_range.end, target_range, val);
self.tree[idx] = (self.merge)(self.tree[idx * 2], self.tree[idx * 2 + 1]);
self.lazy[idx] = Some(T::default());
}
fn propagation(&mut self, idx: usize, element_range: &Range<usize>, parent_lazy: T) {
if element_range.end - element_range.start == 1 {
self.tree[idx] += parent_lazy;
return;
}
let lazy = self.lazy[idx].unwrap_or_default();
self.lazy[idx] = None;
let mid = element_range.start + (element_range.end - element_range.start) / 2;
self.propagation(idx * 2, &(element_range.start..mid), parent_lazy + lazy);
self.propagation(idx * 2 + 1, &(mid..element_range.end), parent_lazy + lazy);
self.tree[idx] = (self.merge)(self.tree[idx * 2], self.tree[idx * 2 + 1]);
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::TestResult;
use quickcheck_macros::quickcheck;
use std::cmp::{max, min};
#[test]
fn test_min_segments() {
let vec = vec![-30, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8];
let mut min_seg_tree = LazySegmentTree::from_vec(&vec, min);
// [-30, 2, -4, 7, (3, -5, 6), 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(-5), min_seg_tree.query(4..7));
// [(-30, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8)]
assert_eq!(Some(-30), min_seg_tree.query(0..vec.len()));
// [(-30, 2), -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(-30), min_seg_tree.query(0..2));
// [-30, (2, -4), 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(-4), min_seg_tree.query(1..3));
// [-30, (2, -4, 7, 3, -5, 6), 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(-5), min_seg_tree.query(1..7));
}
#[test]
fn test_max_segments() {
let vec = vec![-30, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8];
let mut max_seg_tree = LazySegmentTree::from_vec(&vec, max);
// [-30, 2, -4, 7, (3, -5, 6), 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(6), max_seg_tree.query(4..7));
// [(-30, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8)]
assert_eq!(Some(15), max_seg_tree.query(0..vec.len()));
// [(-30, 2), -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(2), max_seg_tree.query(0..2));
// [-30, (2, -4), 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(2), max_seg_tree.query(1..3));
// [-30, (2, -4, 7, 3, -5, 6), 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(7), max_seg_tree.query(1..7));
}
#[test]
fn test_sum_segments() {
let vec = vec![-30, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8];
let mut max_seg_tree = LazySegmentTree::from_vec(&vec, |x, y| x + y);
// [-30, 2, -4, 7, (3, -5, 6), 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(4), max_seg_tree.query(4..7));
// [(-30, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8)]
assert_eq!(Some(7), max_seg_tree.query(0..vec.len()));
// [(-30, 2), -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(-28), max_seg_tree.query(0..2));
// [-30, (2, -4), 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(-2), max_seg_tree.query(1..3));
// [-30, (2, -4, 7, 3, -5, 6), 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(9), max_seg_tree.query(1..7));
}
#[test]
fn test_update_segments_tiny() {
let vec = vec![0, 0, 0, 0, 0];
let mut update_seg_tree = LazySegmentTree::from_vec(&vec, |x, y| x + y);
update_seg_tree.update(0..3, 3);
update_seg_tree.update(2..5, 3);
assert_eq!(Some(3), update_seg_tree.query(0..1));
assert_eq!(Some(3), update_seg_tree.query(1..2));
assert_eq!(Some(6), update_seg_tree.query(2..3));
assert_eq!(Some(3), update_seg_tree.query(3..4));
assert_eq!(Some(3), update_seg_tree.query(4..5));
}
#[test]
fn test_update_segments() {
let vec = vec![-30, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8];
let mut update_seg_tree = LazySegmentTree::from_vec(&vec, |x, y| x + y);
// -> [-30, (5, -1, 10, 6), -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
update_seg_tree.update(1..5, 3);
// [-30, 5, -1, 10, (6 -5, 6), 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(7), update_seg_tree.query(4..7));
// [(-30, 5, -1, 10, 6 , -5, 6, 11, -20, 9, 14, 15, 5, 2, -8)]
assert_eq!(Some(19), update_seg_tree.query(0..vec.len()));
// [(-30, 5), -1, 10, 6, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(-25), update_seg_tree.query(0..2));
// [-30, (5, -1), 10, 6, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(4), update_seg_tree.query(1..3));
// [-30, (5, -1, 10, 6, -5, 6), 11, -20, 9, 14, 15, 5, 2, -8]
assert_eq!(Some(21), update_seg_tree.query(1..7));
}
// Some properties over segment trees:
// When asking for the range of the overall array, return the same as iter().min() or iter().max(), etc.
// When asking for an interval containing a single value, return this value, no matter the merge function
#[quickcheck]
fn check_overall_interval_min(array: Vec<i32>) -> TestResult {
let mut seg_tree = LazySegmentTree::from_vec(&array, min);
TestResult::from_bool(array.iter().min().copied() == seg_tree.query(0..array.len()))
}
#[quickcheck]
fn check_overall_interval_max(array: Vec<i32>) -> TestResult {
let mut seg_tree = LazySegmentTree::from_vec(&array, max);
TestResult::from_bool(array.iter().max().copied() == seg_tree.query(0..array.len()))
}
#[quickcheck]
fn check_overall_interval_sum(array: Vec<i32>) -> TestResult {
let mut seg_tree = LazySegmentTree::from_vec(&array, max);
TestResult::from_bool(array.iter().max().copied() == seg_tree.query(0..array.len()))
}
#[quickcheck]
fn check_single_interval_min(array: Vec<i32>) -> TestResult {
let mut seg_tree = LazySegmentTree::from_vec(&array, min);
for (i, value) in array.into_iter().enumerate() {
let res = seg_tree.query(Range {
start: i,
end: i + 1,
});
if res != Some(value) {
return TestResult::error(format!("Expected {:?}, got {:?}", Some(value), res));
}
}
TestResult::passed()
}
#[quickcheck]
fn check_single_interval_max(array: Vec<i32>) -> TestResult {
let mut seg_tree = LazySegmentTree::from_vec(&array, max);
for (i, value) in array.into_iter().enumerate() {
let res = seg_tree.query(Range {
start: i,
end: i + 1,
});
if res != Some(value) {
return TestResult::error(format!("Expected {:?}, got {:?}", Some(value), res));
}
}
TestResult::passed()
}
#[quickcheck]
fn check_single_interval_sum(array: Vec<i32>) -> TestResult {
let mut seg_tree = LazySegmentTree::from_vec(&array, max);
for (i, value) in array.into_iter().enumerate() {
let res = seg_tree.query(Range {
start: i,
end: i + 1,
});
if res != Some(value) {
return TestResult::error(format!("Expected {:?}, got {:?}", Some(value), res));
}
}
TestResult::passed()
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/veb_tree.rs | src/data_structures/veb_tree.rs | // This struct implements Van Emde Boas tree (VEB tree). It stores integers in range [0, U), where
// O is any integer that is a power of 2. It supports operations such as insert, search,
// predecessor, and successor in O(log(log(U))) time. The structure takes O(U) space.
pub struct VebTree {
size: u32,
child_size: u32, // Set to square root of size. Cache here to avoid recomputation.
min: u32,
max: u32,
summary: Option<Box<VebTree>>,
cluster: Vec<VebTree>,
}
impl VebTree {
/// Create a new, empty VEB tree. The tree will contain number of elements equal to size
/// rounded up to the nearest power of two.
pub fn new(size: u32) -> VebTree {
let rounded_size = size.next_power_of_two();
let child_size = (size as f64).sqrt().ceil() as u32;
let mut cluster = Vec::new();
if rounded_size > 2 {
for _ in 0..rounded_size {
cluster.push(VebTree::new(child_size));
}
}
VebTree {
size: rounded_size,
child_size,
min: u32::MAX,
max: u32::MIN,
cluster,
summary: if rounded_size <= 2 {
None
} else {
Some(Box::new(VebTree::new(child_size)))
},
}
}
fn high(&self, value: u32) -> u32 {
value / self.child_size
}
fn low(&self, value: u32) -> u32 {
value % self.child_size
}
fn index(&self, cluster: u32, offset: u32) -> u32 {
cluster * self.child_size + offset
}
pub fn min(&self) -> u32 {
self.min
}
pub fn max(&self) -> u32 {
self.max
}
pub fn iter(&self) -> VebTreeIter<'_> {
VebTreeIter::new(self)
}
// A VEB tree is empty if the min is greater than the max.
pub fn empty(&self) -> bool {
self.min > self.max
}
// Returns true if value is in the tree, false otherwise.
pub fn search(&self, value: u32) -> bool {
if self.empty() {
return false;
} else if value == self.min || value == self.max {
return true;
} else if value < self.min || value > self.max {
return false;
}
self.cluster[self.high(value) as usize].search(self.low(value))
}
fn insert_empty(&mut self, value: u32) {
assert!(self.empty(), "tree should be empty");
self.min = value;
self.max = value;
}
// Inserts value into the tree.
pub fn insert(&mut self, mut value: u32) {
assert!(value < self.size);
if self.empty() {
self.insert_empty(value);
return;
}
if value < self.min {
// If the new value is less than the current tree's min, set the min to the new value
// and insert the old min.
(value, self.min) = (self.min, value);
}
if self.size > 2 {
// Non base case. The checks for min/max will handle trees of size 2.
let high = self.high(value);
let low = self.low(value);
if self.cluster[high as usize].empty() {
// If the cluster tree for the value is empty, we set the min/max of the tree to
// value and record that the cluster tree has an elements in the summary.
self.cluster[high as usize].insert_empty(low);
if let Some(summary) = self.summary.as_mut() {
summary.insert(high);
}
} else {
// If the cluster tree already has a value, the summary does not need to be
// updated. Recursively insert the value into the cluster tree.
self.cluster[high as usize].insert(low);
}
}
if value > self.max {
self.max = value;
}
}
// Returns the next greatest value(successor) in the tree after pred. Returns
// `None` if there is no successor.
pub fn succ(&self, pred: u32) -> Option<u32> {
if self.empty() {
return None;
}
if self.size == 2 {
// Base case. If pred is 0, and 1 exists in the tree (max is set to 1), the successor
// is 1.
return if pred == 0 && self.max == 1 {
Some(1)
} else {
None
};
}
if pred < self.min {
// If the predecessor is less than the minimum of this tree, the successor is the min.
return Some(self.min);
}
let low = self.low(pred);
let high = self.high(pred);
if !self.cluster[high as usize].empty() && low < self.cluster[high as usize].max {
// The successor is within the same cluster as the predecessor
return Some(self.index(high, self.cluster[high as usize].succ(low).unwrap()));
};
// If we reach this point, the successor exists in a different cluster. We use the summary
// to efficiently query which cluster the successor lives in. If there is no successor
// cluster, return None.
let succ_cluster = self.summary.as_ref().unwrap().succ(high);
succ_cluster
.map(|succ_cluster| self.index(succ_cluster, self.cluster[succ_cluster as usize].min))
}
// Returns the next smallest value(predecessor) in the tree after succ. Returns
// `None` if there is no predecessor. pred() is almost a mirror of succ().
// Differences are noted in comments.
pub fn pred(&self, succ: u32) -> Option<u32> {
if self.empty() {
return None;
}
// base case.
if self.size == 2 {
return if succ == 1 && self.min == 0 {
Some(0)
} else {
None
};
}
if succ > self.max {
return Some(self.max);
}
let low = self.low(succ);
let high = self.high(succ);
if !self.cluster[high as usize].empty() && low > self.cluster[high as usize].min {
return Some(self.index(high, self.cluster[high as usize].pred(low).unwrap()));
};
// Find the cluster that has the predecessor. The successor will be that cluster's max.
let succ_cluster = self.summary.as_ref().unwrap().pred(high);
match succ_cluster {
Some(succ_cluster) => {
Some(self.index(succ_cluster, self.cluster[succ_cluster as usize].max))
}
// Special case for pred() that does not exist in succ(). The current tree's min
// does not exist in a cluster. So if we cannot find a cluster that could have the
// predecessor, the predecessor could be the min of the current tree.
None => {
if succ > self.min {
Some(self.min)
} else {
None
}
}
}
}
}
pub struct VebTreeIter<'a> {
tree: &'a VebTree,
curr: Option<u32>,
}
impl<'a> VebTreeIter<'a> {
pub fn new(tree: &'a VebTree) -> VebTreeIter<'a> {
let curr = if tree.empty() { None } else { Some(tree.min) };
VebTreeIter { tree, curr }
}
}
impl Iterator for VebTreeIter<'_> {
type Item = u32;
fn next(&mut self) -> Option<u32> {
let curr = self.curr;
curr?;
self.curr = self.tree.succ(curr.unwrap());
curr
}
}
#[cfg(test)]
mod test {
use super::VebTree;
use rand::{rngs::StdRng, Rng, SeedableRng};
fn test_veb_tree(size: u32, mut elements: Vec<u32>, exclude: Vec<u32>) {
// Insert elements
let mut tree = VebTree::new(size);
for element in elements.iter() {
tree.insert(*element);
}
// Test search
for element in elements.iter() {
assert!(tree.search(*element));
}
for element in exclude {
assert!(!tree.search(element));
}
// Test iterator and successor, and predecessor
elements.sort();
elements.dedup();
for (i, element) in tree.iter().enumerate() {
assert!(elements[i] == element);
}
for i in 1..elements.len() {
assert!(tree.succ(elements[i - 1]) == Some(elements[i]));
assert!(tree.pred(elements[i]) == Some(elements[i - 1]));
}
}
#[test]
fn test_empty() {
test_veb_tree(16, Vec::new(), (0..16).collect());
}
#[test]
fn test_single() {
test_veb_tree(16, Vec::from([5]), (0..16).filter(|x| *x != 5).collect());
}
#[test]
fn test_two() {
test_veb_tree(
16,
Vec::from([4, 9]),
(0..16).filter(|x| *x != 4 && *x != 9).collect(),
);
}
#[test]
fn test_repeat_insert() {
let mut tree = VebTree::new(16);
for _ in 0..5 {
tree.insert(10);
}
assert!(tree.search(10));
let elements: Vec<u32> = (0..16).filter(|x| *x != 10).collect();
for element in elements {
assert!(!tree.search(element));
}
}
#[test]
fn test_linear() {
test_veb_tree(16, (0..10).collect(), (10..16).collect());
}
fn test_full(size: u32) {
test_veb_tree(size, (0..size).collect(), Vec::new());
}
#[test]
fn test_full_small() {
test_full(8);
test_full(10);
test_full(16);
test_full(20);
test_full(32);
}
#[test]
fn test_full_256() {
test_full(256);
}
#[test]
fn test_10_256() {
let mut rng = StdRng::seed_from_u64(0);
let elements: Vec<u32> = (0..10).map(|_| rng.random_range(0..255)).collect();
test_veb_tree(256, elements, Vec::new());
}
#[test]
fn test_100_256() {
let mut rng = StdRng::seed_from_u64(0);
let elements: Vec<u32> = (0..100).map(|_| rng.random_range(0..255)).collect();
test_veb_tree(256, elements, Vec::new());
}
#[test]
fn test_100_300() {
let mut rng = StdRng::seed_from_u64(0);
let elements: Vec<u32> = (0..100).map(|_| rng.random_range(0..255)).collect();
test_veb_tree(300, elements, Vec::new());
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/graph.rs | src/data_structures/graph.rs | use std::collections::{HashMap, HashSet};
use std::fmt;
#[derive(Debug, Clone)]
pub struct NodeNotInGraph;
impl fmt::Display for NodeNotInGraph {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "accessing a node that is not in the graph")
}
}
pub struct DirectedGraph {
adjacency_table: HashMap<String, Vec<(String, i32)>>,
}
impl Graph for DirectedGraph {
fn new() -> DirectedGraph {
DirectedGraph {
adjacency_table: HashMap::new(),
}
}
fn adjacency_table_mutable(&mut self) -> &mut HashMap<String, Vec<(String, i32)>> {
&mut self.adjacency_table
}
fn adjacency_table(&self) -> &HashMap<String, Vec<(String, i32)>> {
&self.adjacency_table
}
}
pub struct UndirectedGraph {
adjacency_table: HashMap<String, Vec<(String, i32)>>,
}
impl Graph for UndirectedGraph {
fn new() -> UndirectedGraph {
UndirectedGraph {
adjacency_table: HashMap::new(),
}
}
fn adjacency_table_mutable(&mut self) -> &mut HashMap<String, Vec<(String, i32)>> {
&mut self.adjacency_table
}
fn adjacency_table(&self) -> &HashMap<String, Vec<(String, i32)>> {
&self.adjacency_table
}
fn add_edge(&mut self, edge: (&str, &str, i32)) {
self.add_node(edge.0);
self.add_node(edge.1);
self.adjacency_table
.entry(edge.0.to_string())
.and_modify(|e| {
e.push((edge.1.to_string(), edge.2));
});
self.adjacency_table
.entry(edge.1.to_string())
.and_modify(|e| {
e.push((edge.0.to_string(), edge.2));
});
}
}
pub trait Graph {
fn new() -> Self;
fn adjacency_table_mutable(&mut self) -> &mut HashMap<String, Vec<(String, i32)>>;
fn adjacency_table(&self) -> &HashMap<String, Vec<(String, i32)>>;
fn add_node(&mut self, node: &str) -> bool {
match self.adjacency_table().get(node) {
None => {
self.adjacency_table_mutable()
.insert((*node).to_string(), Vec::new());
true
}
_ => false,
}
}
fn add_edge(&mut self, edge: (&str, &str, i32)) {
self.add_node(edge.0);
self.add_node(edge.1);
self.adjacency_table_mutable()
.entry(edge.0.to_string())
.and_modify(|e| {
e.push((edge.1.to_string(), edge.2));
});
}
fn neighbours(&self, node: &str) -> Result<&Vec<(String, i32)>, NodeNotInGraph> {
match self.adjacency_table().get(node) {
None => Err(NodeNotInGraph),
Some(i) => Ok(i),
}
}
fn contains(&self, node: &str) -> bool {
self.adjacency_table().get(node).is_some()
}
fn nodes(&self) -> HashSet<&String> {
self.adjacency_table().keys().collect()
}
fn edges(&self) -> Vec<(&String, &String, i32)> {
let mut edges = Vec::new();
for (from_node, from_node_neighbours) in self.adjacency_table() {
for (to_node, weight) in from_node_neighbours {
edges.push((from_node, to_node, *weight));
}
}
edges
}
}
#[cfg(test)]
mod test_undirected_graph {
use super::Graph;
use super::UndirectedGraph;
#[test]
fn test_add_edge() {
let mut graph = UndirectedGraph::new();
graph.add_edge(("a", "b", 5));
graph.add_edge(("b", "c", 10));
graph.add_edge(("c", "a", 7));
let expected_edges = [
(&String::from("a"), &String::from("b"), 5),
(&String::from("b"), &String::from("a"), 5),
(&String::from("c"), &String::from("a"), 7),
(&String::from("a"), &String::from("c"), 7),
(&String::from("b"), &String::from("c"), 10),
(&String::from("c"), &String::from("b"), 10),
];
for edge in expected_edges.iter() {
assert!(graph.edges().contains(edge));
}
}
#[test]
fn test_neighbours() {
let mut graph = UndirectedGraph::new();
graph.add_edge(("a", "b", 5));
graph.add_edge(("b", "c", 10));
graph.add_edge(("c", "a", 7));
assert_eq!(
graph.neighbours("a").unwrap(),
&vec![(String::from("b"), 5), (String::from("c"), 7)]
);
}
}
#[cfg(test)]
mod test_directed_graph {
use super::DirectedGraph;
use super::Graph;
#[test]
fn test_add_node() {
let mut graph = DirectedGraph::new();
graph.add_node("a");
graph.add_node("b");
graph.add_node("c");
assert_eq!(
graph.nodes(),
[&String::from("a"), &String::from("b"), &String::from("c")]
.iter()
.cloned()
.collect()
);
}
#[test]
fn test_add_edge() {
let mut graph = DirectedGraph::new();
graph.add_edge(("a", "b", 5));
graph.add_edge(("c", "a", 7));
graph.add_edge(("b", "c", 10));
let expected_edges = [
(&String::from("a"), &String::from("b"), 5),
(&String::from("c"), &String::from("a"), 7),
(&String::from("b"), &String::from("c"), 10),
];
for edge in expected_edges.iter() {
assert!(graph.edges().contains(edge));
}
}
#[test]
fn test_neighbours() {
let mut graph = DirectedGraph::new();
graph.add_edge(("a", "b", 5));
graph.add_edge(("b", "c", 10));
graph.add_edge(("c", "a", 7));
assert_eq!(
graph.neighbours("a").unwrap(),
&vec![(String::from("b"), 5)]
);
}
#[test]
fn test_contains() {
let mut graph = DirectedGraph::new();
graph.add_node("a");
graph.add_node("b");
graph.add_node("c");
assert!(graph.contains("a"));
assert!(graph.contains("b"));
assert!(graph.contains("c"));
assert!(!graph.contains("d"));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/avl_tree.rs | src/data_structures/avl_tree.rs | use std::{
cmp::{max, Ordering},
iter::FromIterator,
mem,
ops::Not,
};
/// An internal node of an `AVLTree`.
struct AVLNode<T: Ord> {
value: T,
height: usize,
left: Option<Box<AVLNode<T>>>,
right: Option<Box<AVLNode<T>>>,
}
/// A set based on an AVL Tree.
///
/// An AVL Tree is a self-balancing binary search tree. It tracks the height of each node
/// and performs internal rotations to maintain a height difference of at most 1 between
/// each sibling pair.
pub struct AVLTree<T: Ord> {
root: Option<Box<AVLNode<T>>>,
length: usize,
}
/// Refers to the left or right subtree of an `AVLNode`.
#[derive(Clone, Copy)]
enum Side {
Left,
Right,
}
impl<T: Ord> AVLTree<T> {
/// Creates an empty `AVLTree`.
pub fn new() -> AVLTree<T> {
AVLTree {
root: None,
length: 0,
}
}
/// Returns `true` if the tree contains a value.
pub fn contains(&self, value: &T) -> bool {
let mut current = &self.root;
while let Some(node) = current {
current = match value.cmp(&node.value) {
Ordering::Equal => return true,
Ordering::Less => &node.left,
Ordering::Greater => &node.right,
}
}
false
}
/// Adds a value to the tree.
///
/// Returns `true` if the tree did not yet contain the value.
pub fn insert(&mut self, value: T) -> bool {
let inserted = insert(&mut self.root, value);
if inserted {
self.length += 1;
}
inserted
}
/// Removes a value from the tree.
///
/// Returns `true` if the tree contained the value.
pub fn remove(&mut self, value: &T) -> bool {
let removed = remove(&mut self.root, value);
if removed {
self.length -= 1;
}
removed
}
/// Returns the number of values in the tree.
pub fn len(&self) -> usize {
self.length
}
/// Returns `true` if the tree contains no values.
pub fn is_empty(&self) -> bool {
self.length == 0
}
/// Returns an iterator that visits the nodes in the tree in order.
fn node_iter(&self) -> NodeIter<'_, T> {
let cap = self.root.as_ref().map_or(0, |n| n.height);
let mut node_iter = NodeIter {
stack: Vec::with_capacity(cap),
};
// Initialize stack with path to leftmost child
let mut child = &self.root;
while let Some(node) = child {
node_iter.stack.push(node.as_ref());
child = &node.left;
}
node_iter
}
/// Returns an iterator that visits the values in the tree in ascending order.
pub fn iter(&self) -> Iter<'_, T> {
Iter {
node_iter: self.node_iter(),
}
}
}
/// Recursive helper function for `AVLTree` insertion.
fn insert<T: Ord>(tree: &mut Option<Box<AVLNode<T>>>, value: T) -> bool {
if let Some(node) = tree {
let inserted = match value.cmp(&node.value) {
Ordering::Equal => false,
Ordering::Less => insert(&mut node.left, value),
Ordering::Greater => insert(&mut node.right, value),
};
if inserted {
node.rebalance();
}
inserted
} else {
*tree = Some(Box::new(AVLNode {
value,
height: 1,
left: None,
right: None,
}));
true
}
}
/// Recursive helper function for `AVLTree` deletion.
fn remove<T: Ord>(tree: &mut Option<Box<AVLNode<T>>>, value: &T) -> bool {
if let Some(node) = tree {
let removed = match value.cmp(&node.value) {
Ordering::Less => remove(&mut node.left, value),
Ordering::Greater => remove(&mut node.right, value),
Ordering::Equal => {
*tree = match (node.left.take(), node.right.take()) {
(None, None) => None,
(Some(b), None) | (None, Some(b)) => Some(b),
(Some(left), Some(right)) => Some(merge(left, right)),
};
return true;
}
};
if removed {
node.rebalance();
}
removed
} else {
false
}
}
/// Merges two trees and returns the root of the merged tree.
fn merge<T: Ord>(left: Box<AVLNode<T>>, right: Box<AVLNode<T>>) -> Box<AVLNode<T>> {
let mut op_right = Some(right);
// Guaranteed not to panic since right has at least one node
let mut root = take_min(&mut op_right).unwrap();
root.left = Some(left);
root.right = op_right;
root.rebalance();
root
}
/// Removes the smallest node from the tree, if one exists.
fn take_min<T: Ord>(tree: &mut Option<Box<AVLNode<T>>>) -> Option<Box<AVLNode<T>>> {
if let Some(mut node) = tree.take() {
// Recurse along the left side
if let Some(small) = take_min(&mut node.left) {
// Took the smallest from below; update this node and put it back in the tree
node.rebalance();
*tree = Some(node);
Some(small)
} else {
// Take this node and replace it with its right child
*tree = node.right.take();
Some(node)
}
} else {
None
}
}
impl<T: Ord> AVLNode<T> {
/// Returns a reference to the left or right child.
fn child(&self, side: Side) -> &Option<Box<AVLNode<T>>> {
match side {
Side::Left => &self.left,
Side::Right => &self.right,
}
}
/// Returns a mutable reference to the left or right child.
fn child_mut(&mut self, side: Side) -> &mut Option<Box<AVLNode<T>>> {
match side {
Side::Left => &mut self.left,
Side::Right => &mut self.right,
}
}
/// Returns the height of the left or right subtree.
fn height(&self, side: Side) -> usize {
self.child(side).as_ref().map_or(0, |n| n.height)
}
/// Returns the height difference between the left and right subtrees.
fn balance_factor(&self) -> i8 {
let (left, right) = (self.height(Side::Left), self.height(Side::Right));
if left < right {
(right - left) as i8
} else {
-((left - right) as i8)
}
}
/// Recomputes the `height` field.
fn update_height(&mut self) {
self.height = 1 + max(self.height(Side::Left), self.height(Side::Right));
}
/// Performs a left or right rotation.
fn rotate(&mut self, side: Side) {
let mut subtree = self.child_mut(!side).take().unwrap();
*self.child_mut(!side) = subtree.child_mut(side).take();
self.update_height();
// Swap root and child nodes in memory
mem::swap(self, subtree.as_mut());
// Set old root (subtree) as child of new root (self)
*self.child_mut(side) = Some(subtree);
self.update_height();
}
/// Performs left or right tree rotations to balance this node.
fn rebalance(&mut self) {
self.update_height();
let side = match self.balance_factor() {
-2 => Side::Left,
2 => Side::Right,
_ => return,
};
let subtree = self.child_mut(side).as_mut().unwrap();
// Left-Right and Right-Left require rotation of heavy subtree
if let (Side::Left, 1) | (Side::Right, -1) = (side, subtree.balance_factor()) {
subtree.rotate(side);
}
// Rotate in opposite direction of heavy side
self.rotate(!side);
}
}
impl<T: Ord> Default for AVLTree<T> {
fn default() -> Self {
Self::new()
}
}
impl Not for Side {
type Output = Side;
fn not(self) -> Self::Output {
match self {
Side::Left => Side::Right,
Side::Right => Side::Left,
}
}
}
impl<T: Ord> FromIterator<T> for AVLTree<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut tree = AVLTree::new();
for value in iter {
tree.insert(value);
}
tree
}
}
/// An iterator over the nodes of an `AVLTree`.
///
/// This struct is created by the `node_iter` method of `AVLTree`.
struct NodeIter<'a, T: Ord> {
stack: Vec<&'a AVLNode<T>>,
}
impl<'a, T: Ord> Iterator for NodeIter<'a, T> {
type Item = &'a AVLNode<T>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(node) = self.stack.pop() {
// Push left path of right subtree to stack
let mut child = &node.right;
while let Some(subtree) = child {
self.stack.push(subtree.as_ref());
child = &subtree.left;
}
Some(node)
} else {
None
}
}
}
/// An iterator over the items of an `AVLTree`.
///
/// This struct is created by the `iter` method of `AVLTree`.
pub struct Iter<'a, T: Ord> {
node_iter: NodeIter<'a, T>,
}
impl<'a, T: Ord> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
match self.node_iter.next() {
Some(node) => Some(&node.value),
None => None,
}
}
}
#[cfg(test)]
mod tests {
use super::AVLTree;
/// Returns `true` if all nodes in the tree are balanced.
fn is_balanced<T: Ord>(tree: &AVLTree<T>) -> bool {
tree.node_iter()
.all(|n| (-1..=1).contains(&n.balance_factor()))
}
#[test]
fn len() {
let tree: AVLTree<_> = (1..4).collect();
assert_eq!(tree.len(), 3);
}
#[test]
fn contains() {
let tree: AVLTree<_> = (1..4).collect();
assert!(tree.contains(&1));
assert!(!tree.contains(&4));
}
#[test]
fn insert() {
let mut tree = AVLTree::new();
// First insert succeeds
assert!(tree.insert(1));
// Second insert fails
assert!(!tree.insert(1));
}
#[test]
fn remove() {
let mut tree: AVLTree<_> = (1..8).collect();
// First remove succeeds
assert!(tree.remove(&4));
// Second remove fails
assert!(!tree.remove(&4));
}
#[test]
fn sorted() {
let tree: AVLTree<_> = (1..8).rev().collect();
assert!((1..8).eq(tree.iter().copied()));
}
#[test]
fn balanced() {
let mut tree: AVLTree<_> = (1..8).collect();
assert!(is_balanced(&tree));
for x in 1..8 {
tree.remove(&x);
assert!(is_balanced(&tree));
}
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/fenwick_tree.rs | src/data_structures/fenwick_tree.rs | use std::ops::{Add, AddAssign, Sub, SubAssign};
/// A Fenwick Tree (also known as a Binary Indexed Tree) that supports efficient
/// prefix sum, range sum and point queries, as well as point updates.
///
/// The Fenwick Tree uses **1-based** indexing internally but presents a **0-based** interface to the user.
/// This design improves efficiency and simplifies both internal operations and external usage.
pub struct FenwickTree<T>
where
T: Add<Output = T> + AddAssign + Sub<Output = T> + SubAssign + Copy + Default,
{
/// Internal storage of the Fenwick Tree. The first element (index 0) is unused
/// to simplify index calculations, so the effective tree size is `data.len() - 1`.
data: Vec<T>,
}
/// Enum representing the possible errors that can occur during FenwickTree operations.
#[derive(Debug, PartialEq, Eq)]
pub enum FenwickTreeError {
/// Error indicating that an index was out of the valid range.
IndexOutOfBounds,
/// Error indicating that a provided range was invalid (e.g., left > right).
InvalidRange,
}
impl<T> FenwickTree<T>
where
T: Add<Output = T> + AddAssign + Sub<Output = T> + SubAssign + Copy + Default,
{
/// Creates a new Fenwick Tree with a specified capacity.
///
/// The tree will have `capacity + 1` elements, all initialized to the default
/// value of type `T`. The additional element allows for 1-based indexing internally.
///
/// # Arguments
///
/// * `capacity` - The number of elements the tree can hold (excluding the extra element).
///
/// # Returns
///
/// A new `FenwickTree` instance.
pub fn with_capacity(capacity: usize) -> Self {
FenwickTree {
data: vec![T::default(); capacity + 1],
}
}
/// Updates the tree by adding a value to the element at a specified index.
///
/// This operation also propagates the update to subsequent elements in the tree.
///
/// # Arguments
///
/// * `index` - The zero-based index where the value should be added.
/// * `value` - The value to add to the element at the specified index.
///
/// # Returns
///
/// A `Result` indicating success (`Ok`) or an error (`FenwickTreeError::IndexOutOfBounds`)
/// if the index is out of bounds.
pub fn update(&mut self, index: usize, value: T) -> Result<(), FenwickTreeError> {
if index >= self.data.len() - 1 {
return Err(FenwickTreeError::IndexOutOfBounds);
}
let mut idx = index + 1;
while idx < self.data.len() {
self.data[idx] += value;
idx += lowbit(idx);
}
Ok(())
}
/// Computes the sum of elements from the start of the tree up to a specified index.
///
/// This operation efficiently calculates the prefix sum using the tree structure.
///
/// # Arguments
///
/// * `index` - The zero-based index up to which the sum should be computed.
///
/// # Returns
///
/// A `Result` containing the prefix sum (`Ok(sum)`) or an error (`FenwickTreeError::IndexOutOfBounds`)
/// if the index is out of bounds.
pub fn prefix_query(&self, index: usize) -> Result<T, FenwickTreeError> {
if index >= self.data.len() - 1 {
return Err(FenwickTreeError::IndexOutOfBounds);
}
let mut idx = index + 1;
let mut result = T::default();
while idx > 0 {
result += self.data[idx];
idx -= lowbit(idx);
}
Ok(result)
}
/// Computes the sum of elements within a specified range `[left, right]`.
///
/// This operation calculates the range sum by performing two prefix sum queries.
///
/// # Arguments
///
/// * `left` - The zero-based starting index of the range.
/// * `right` - The zero-based ending index of the range.
///
/// # Returns
///
/// A `Result` containing the range sum (`Ok(sum)`) or an error (`FenwickTreeError::InvalidRange`)
/// if the left index is greater than the right index or the right index is out of bounds.
pub fn range_query(&self, left: usize, right: usize) -> Result<T, FenwickTreeError> {
if left > right || right >= self.data.len() - 1 {
return Err(FenwickTreeError::InvalidRange);
}
let right_query = self.prefix_query(right)?;
let left_query = if left == 0 {
T::default()
} else {
self.prefix_query(left - 1)?
};
Ok(right_query - left_query)
}
/// Retrieves the value at a specific index by isolating it from the prefix sum.
///
/// This operation determines the value at `index` by subtracting the prefix sum up to `index - 1`
/// from the prefix sum up to `index`.
///
/// # Arguments
///
/// * `index` - The zero-based index of the element to retrieve.
///
/// # Returns
///
/// A `Result` containing the value at the specified index (`Ok(value)`) or an error (`FenwickTreeError::IndexOutOfBounds`)
/// if the index is out of bounds.
pub fn point_query(&self, index: usize) -> Result<T, FenwickTreeError> {
if index >= self.data.len() - 1 {
return Err(FenwickTreeError::IndexOutOfBounds);
}
let index_query = self.prefix_query(index)?;
let prev_query = if index == 0 {
T::default()
} else {
self.prefix_query(index - 1)?
};
Ok(index_query - prev_query)
}
/// Sets the value at a specific index in the tree, updating the structure accordingly.
///
/// This operation updates the value at `index` by computing the difference between the
/// desired value and the current value, then applying that difference using `update`.
///
/// # Arguments
///
/// * `index` - The zero-based index of the element to set.
/// * `value` - The new value to set at the specified index.
///
/// # Returns
///
/// A `Result` indicating success (`Ok`) or an error (`FenwickTreeError::IndexOutOfBounds`)
/// if the index is out of bounds.
pub fn set(&mut self, index: usize, value: T) -> Result<(), FenwickTreeError> {
self.update(index, value - self.point_query(index)?)
}
}
/// Computes the lowest set bit (rightmost `1` bit) of a number.
///
/// This function isolates the lowest set bit in the binary representation of `x`.
/// It's used to navigate the Fenwick Tree by determining the next index to update or query.
///
///
/// In a Fenwick Tree, operations like updating and querying use bitwise manipulation
/// (via the lowbit function). These operations naturally align with 1-based indexing,
/// making traversal between parent and child nodes more straightforward.
///
/// # Arguments
///
/// * `x` - The input number whose lowest set bit is to be determined.
///
/// # Returns
///
/// The value of the lowest set bit in `x`.
const fn lowbit(x: usize) -> usize {
x & (!x + 1)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fenwick_tree() {
let mut fenwick_tree = FenwickTree::with_capacity(10);
assert_eq!(fenwick_tree.update(0, 5), Ok(()));
assert_eq!(fenwick_tree.update(1, 3), Ok(()));
assert_eq!(fenwick_tree.update(2, -2), Ok(()));
assert_eq!(fenwick_tree.update(3, 6), Ok(()));
assert_eq!(fenwick_tree.update(4, -4), Ok(()));
assert_eq!(fenwick_tree.update(5, 7), Ok(()));
assert_eq!(fenwick_tree.update(6, -1), Ok(()));
assert_eq!(fenwick_tree.update(7, 2), Ok(()));
assert_eq!(fenwick_tree.update(8, -3), Ok(()));
assert_eq!(fenwick_tree.update(9, 4), Ok(()));
assert_eq!(fenwick_tree.set(3, 10), Ok(()));
assert_eq!(fenwick_tree.point_query(3), Ok(10));
assert_eq!(fenwick_tree.set(5, 0), Ok(()));
assert_eq!(fenwick_tree.point_query(5), Ok(0));
assert_eq!(
fenwick_tree.update(10, 11),
Err(FenwickTreeError::IndexOutOfBounds)
);
assert_eq!(
fenwick_tree.set(10, 11),
Err(FenwickTreeError::IndexOutOfBounds)
);
assert_eq!(fenwick_tree.prefix_query(0), Ok(5));
assert_eq!(fenwick_tree.prefix_query(1), Ok(8));
assert_eq!(fenwick_tree.prefix_query(2), Ok(6));
assert_eq!(fenwick_tree.prefix_query(3), Ok(16));
assert_eq!(fenwick_tree.prefix_query(4), Ok(12));
assert_eq!(fenwick_tree.prefix_query(5), Ok(12));
assert_eq!(fenwick_tree.prefix_query(6), Ok(11));
assert_eq!(fenwick_tree.prefix_query(7), Ok(13));
assert_eq!(fenwick_tree.prefix_query(8), Ok(10));
assert_eq!(fenwick_tree.prefix_query(9), Ok(14));
assert_eq!(
fenwick_tree.prefix_query(10),
Err(FenwickTreeError::IndexOutOfBounds)
);
assert_eq!(fenwick_tree.range_query(0, 4), Ok(12));
assert_eq!(fenwick_tree.range_query(3, 7), Ok(7));
assert_eq!(fenwick_tree.range_query(2, 5), Ok(4));
assert_eq!(
fenwick_tree.range_query(4, 3),
Err(FenwickTreeError::InvalidRange)
);
assert_eq!(
fenwick_tree.range_query(2, 10),
Err(FenwickTreeError::InvalidRange)
);
assert_eq!(fenwick_tree.point_query(0), Ok(5));
assert_eq!(fenwick_tree.point_query(4), Ok(-4));
assert_eq!(fenwick_tree.point_query(9), Ok(4));
assert_eq!(
fenwick_tree.point_query(10),
Err(FenwickTreeError::IndexOutOfBounds)
);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/queue.rs | src/data_structures/queue.rs | //! This module provides a generic `Queue` data structure, implemented using
//! Rust's `LinkedList` from the standard library. The queue follows the FIFO
//! (First-In-First-Out) principle, where elements are added to the back of
//! the queue and removed from the front.
use std::collections::LinkedList;
#[derive(Debug)]
pub struct Queue<T> {
elements: LinkedList<T>,
}
impl<T> Queue<T> {
// Creates a new empty Queue
pub fn new() -> Queue<T> {
Queue {
elements: LinkedList::new(),
}
}
// Adds an element to the back of the queue
pub fn enqueue(&mut self, value: T) {
self.elements.push_back(value)
}
// Removes and returns the front element from the queue, or None if empty
pub fn dequeue(&mut self) -> Option<T> {
self.elements.pop_front()
}
// Returns a reference to the front element of the queue, or None if empty
pub fn peek_front(&self) -> Option<&T> {
self.elements.front()
}
// Returns a reference to the back element of the queue, or None if empty
pub fn peek_back(&self) -> Option<&T> {
self.elements.back()
}
// Returns the number of elements in the queue
pub fn len(&self) -> usize {
self.elements.len()
}
// Checks if the queue is empty
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
// Clears all elements from the queue
pub fn drain(&mut self) {
self.elements.clear();
}
}
// Implementing the Default trait for Queue
impl<T> Default for Queue<T> {
fn default() -> Queue<T> {
Queue::new()
}
}
#[cfg(test)]
mod tests {
use super::Queue;
#[test]
fn test_queue_functionality() {
let mut queue: Queue<usize> = Queue::default();
assert!(queue.is_empty());
queue.enqueue(8);
queue.enqueue(16);
assert!(!queue.is_empty());
assert_eq!(queue.len(), 2);
assert_eq!(queue.peek_front(), Some(&8));
assert_eq!(queue.peek_back(), Some(&16));
assert_eq!(queue.dequeue(), Some(8));
assert_eq!(queue.len(), 1);
assert_eq!(queue.peek_front(), Some(&16));
assert_eq!(queue.peek_back(), Some(&16));
queue.drain();
assert!(queue.is_empty());
assert_eq!(queue.len(), 0);
assert_eq!(queue.dequeue(), None);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/trie.rs | src/data_structures/trie.rs | //! This module provides a generic implementation of a Trie (prefix tree).
//! A Trie is a tree-like data structure that is commonly used to store sequences of keys
//! (such as strings, integers, or other iterable types) where each node represents one element
//! of the key, and values can be associated with full sequences.
use std::collections::HashMap;
use std::hash::Hash;
/// A single node in the Trie structure, representing a key and an optional value.
#[derive(Debug, Default)]
struct Node<Key: Default, Type: Default> {
/// A map of children nodes where each key maps to another `Node`.
children: HashMap<Key, Node<Key, Type>>,
/// The value associated with this node, if any.
value: Option<Type>,
}
/// A generic Trie (prefix tree) data structure that allows insertion and lookup
/// based on a sequence of keys.
#[derive(Debug, Default)]
pub struct Trie<Key, Type>
where
Key: Default + Eq + Hash,
Type: Default,
{
/// The root node of the Trie, which does not hold a value itself.
root: Node<Key, Type>,
}
impl<Key, Type> Trie<Key, Type>
where
Key: Default + Eq + Hash,
Type: Default,
{
/// Creates a new, empty `Trie`.
///
/// # Returns
/// A `Trie` instance with an empty root node.
pub fn new() -> Self {
Self {
root: Node::default(),
}
}
/// Inserts a value into the Trie, associating it with a sequence of keys.
///
/// # Arguments
/// - `key`: An iterable sequence of keys (e.g., characters in a string or integers in a vector).
/// - `value`: The value to associate with the sequence of keys.
pub fn insert(&mut self, key: impl IntoIterator<Item = Key>, value: Type)
where
Key: Eq + Hash,
{
let mut node = &mut self.root;
for c in key {
node = node.children.entry(c).or_default();
}
node.value = Some(value);
}
/// Retrieves a reference to the value associated with a sequence of keys, if it exists.
///
/// # Arguments
/// - `key`: An iterable sequence of keys (e.g., characters in a string or integers in a vector).
///
/// # Returns
/// An `Option` containing a reference to the value if the sequence of keys exists in the Trie,
/// or `None` if it does not.
pub fn get(&self, key: impl IntoIterator<Item = Key>) -> Option<&Type>
where
Key: Eq + Hash,
{
let mut node = &self.root;
for c in key {
node = node.children.get(&c)?;
}
node.value.as_ref()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_insertion_and_retrieval_with_strings() {
let mut trie = Trie::new();
trie.insert("foo".chars(), 1);
assert_eq!(trie.get("foo".chars()), Some(&1));
trie.insert("foobar".chars(), 2);
assert_eq!(trie.get("foobar".chars()), Some(&2));
assert_eq!(trie.get("foo".chars()), Some(&1));
trie.insert("bar".chars(), 3);
assert_eq!(trie.get("bar".chars()), Some(&3));
assert_eq!(trie.get("baz".chars()), None);
assert_eq!(trie.get("foobarbaz".chars()), None);
}
#[test]
fn test_insertion_and_retrieval_with_integers() {
let mut trie = Trie::new();
trie.insert(vec![1, 2, 3], 1);
assert_eq!(trie.get(vec![1, 2, 3]), Some(&1));
trie.insert(vec![1, 2, 3, 4, 5], 2);
assert_eq!(trie.get(vec![1, 2, 3, 4, 5]), Some(&2));
assert_eq!(trie.get(vec![1, 2, 3]), Some(&1));
trie.insert(vec![10, 20, 30], 3);
assert_eq!(trie.get(vec![10, 20, 30]), Some(&3));
assert_eq!(trie.get(vec![4, 5, 6]), None);
assert_eq!(trie.get(vec![1, 2, 3, 4, 5, 6]), None);
}
#[test]
fn test_empty_trie() {
let trie: Trie<char, i32> = Trie::new();
assert_eq!(trie.get("foo".chars()), None);
assert_eq!(trie.get("".chars()), None);
}
#[test]
fn test_insert_empty_key() {
let mut trie: Trie<char, i32> = Trie::new();
trie.insert("".chars(), 42);
assert_eq!(trie.get("".chars()), Some(&42));
assert_eq!(trie.get("foo".chars()), None);
}
#[test]
fn test_overlapping_keys() {
let mut trie = Trie::new();
trie.insert("car".chars(), 1);
trie.insert("cart".chars(), 2);
trie.insert("carter".chars(), 3);
assert_eq!(trie.get("car".chars()), Some(&1));
assert_eq!(trie.get("cart".chars()), Some(&2));
assert_eq!(trie.get("carter".chars()), Some(&3));
assert_eq!(trie.get("care".chars()), None);
}
#[test]
fn test_partial_match() {
let mut trie = Trie::new();
trie.insert("apple".chars(), 10);
assert_eq!(trie.get("app".chars()), None);
assert_eq!(trie.get("appl".chars()), None);
assert_eq!(trie.get("apple".chars()), Some(&10));
assert_eq!(trie.get("applepie".chars()), None);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/segment_tree_recursive.rs | src/data_structures/segment_tree_recursive.rs | use std::fmt::Debug;
use std::ops::Range;
/// Custom error types representing possible errors that can occur during operations on the `SegmentTree`.
#[derive(Debug, PartialEq, Eq)]
pub enum SegmentTreeError {
/// Error indicating that an index is out of bounds.
IndexOutOfBounds,
/// Error indicating that a range provided for a query is invalid.
InvalidRange,
}
/// A data structure representing a Segment Tree. Which is used for efficient
/// range queries and updates on an array of elements.
pub struct SegmentTree<T, F>
where
T: Debug + Default + Ord + Copy,
F: Fn(T, T) -> T,
{
/// The number of elements in the original input array for which the segment tree is built.
size: usize,
/// A vector representing the nodes of the segment tree.
nodes: Vec<T>,
/// A function that merges two elements of type `T`.
merge_fn: F,
}
impl<T, F> SegmentTree<T, F>
where
T: Debug + Default + Ord + Copy,
F: Fn(T, T) -> T,
{
/// Creates a new `SegmentTree` from the provided slice of elements.
///
/// # Arguments
///
/// * `arr`: A slice of elements of type `T` that initializes the segment tree.
/// * `merge_fn`: A merging function that specifies how to combine two elements of type `T`.
///
/// # Returns
///
/// A new `SegmentTree` instance initialized with the given elements.
pub fn from_vec(arr: &[T], merge_fn: F) -> Self {
let size = arr.len();
let mut seg_tree = SegmentTree {
size,
nodes: vec![T::default(); 4 * size],
merge_fn,
};
if size != 0 {
seg_tree.build_recursive(arr, 1, 0..size);
}
seg_tree
}
/// Recursively builds the segment tree from the provided array.
///
/// # Parameters
///
/// * `arr` - The original array of values.
/// * `node_idx` - The index of the current node in the segment tree.
/// * `node_range` - The range of elements in the original array that the current node covers.
fn build_recursive(&mut self, arr: &[T], node_idx: usize, node_range: Range<usize>) {
if node_range.end - node_range.start == 1 {
self.nodes[node_idx] = arr[node_range.start];
} else {
let mid = node_range.start + (node_range.end - node_range.start) / 2;
self.build_recursive(arr, 2 * node_idx, node_range.start..mid);
self.build_recursive(arr, 2 * node_idx + 1, mid..node_range.end);
self.nodes[node_idx] =
(self.merge_fn)(self.nodes[2 * node_idx], self.nodes[2 * node_idx + 1]);
}
}
/// Queries the segment tree for the result of merging the elements in the specified range.
///
/// # Arguments
///
/// * `target_range`: A range specified as `Range<usize>`, indicating the start (inclusive)
/// and end (exclusive) indices of the segment to query.
///
/// # Returns
///
/// * `Ok(Some(result))` if the query is successful and there are elements in the range,
/// * `Ok(None)` if the range is empty,
/// * `Err(SegmentTreeError::InvalidRange)` if the provided range is invalid.
pub fn query(&self, target_range: Range<usize>) -> Result<Option<T>, SegmentTreeError> {
if target_range.start >= self.size || target_range.end > self.size {
return Err(SegmentTreeError::InvalidRange);
}
Ok(self.query_recursive(1, 0..self.size, &target_range))
}
/// Recursively performs a range query to find the merged result of the specified range.
///
/// # Parameters
///
/// * `node_idx` - The index of the current node in the segment tree.
/// * `tree_range` - The range of elements covered by the current node.
/// * `target_range` - The range for which the query is being performed.
///
/// # Returns
///
/// An `Option<T>` containing the result of the merge operation on the range if within bounds,
/// or `None` if the range is outside the covered range.
fn query_recursive(
&self,
node_idx: usize,
tree_range: Range<usize>,
target_range: &Range<usize>,
) -> Option<T> {
if tree_range.start >= target_range.end || tree_range.end <= target_range.start {
return None;
}
if tree_range.start >= target_range.start && tree_range.end <= target_range.end {
return Some(self.nodes[node_idx]);
}
let mid = tree_range.start + (tree_range.end - tree_range.start) / 2;
let left_res = self.query_recursive(node_idx * 2, tree_range.start..mid, target_range);
let right_res = self.query_recursive(node_idx * 2 + 1, mid..tree_range.end, target_range);
match (left_res, right_res) {
(None, None) => None,
(None, Some(r)) => Some(r),
(Some(l), None) => Some(l),
(Some(l), Some(r)) => Some((self.merge_fn)(l, r)),
}
}
/// Updates the value at the specified index in the segment tree.
///
/// # Arguments
///
/// * `target_idx`: The index (0-based) of the element to update.
/// * `val`: The new value of type `T` to set at the specified index.
///
/// # Returns
///
/// * `Ok(())` if the update was successful,
/// * `Err(SegmentTreeError::IndexOutOfBounds)` if the index is out of bounds.
pub fn update(&mut self, target_idx: usize, val: T) -> Result<(), SegmentTreeError> {
if target_idx >= self.size {
return Err(SegmentTreeError::IndexOutOfBounds);
}
self.update_recursive(1, 0..self.size, target_idx, val);
Ok(())
}
/// Recursively updates the segment tree for a specific index with a new value.
///
/// # Parameters
///
/// * `node_idx` - The index of the current node in the segment tree.
/// * `tree_range` - The range of elements covered by the current node.
/// * `target_idx` - The index in the original array to update.
/// * `val` - The new value to set at `target_idx`.
fn update_recursive(
&mut self,
node_idx: usize,
tree_range: Range<usize>,
target_idx: usize,
val: T,
) {
if tree_range.start > target_idx || tree_range.end <= target_idx {
return;
}
if tree_range.end - tree_range.start <= 1 && tree_range.start == target_idx {
self.nodes[node_idx] = val;
return;
}
let mid = tree_range.start + (tree_range.end - tree_range.start) / 2;
self.update_recursive(node_idx * 2, tree_range.start..mid, target_idx, val);
self.update_recursive(node_idx * 2 + 1, mid..tree_range.end, target_idx, val);
self.nodes[node_idx] =
(self.merge_fn)(self.nodes[node_idx * 2], self.nodes[node_idx * 2 + 1]);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cmp::{max, min};
#[test]
fn test_min_segments() {
let vec = vec![-30, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8];
let mut min_seg_tree = SegmentTree::from_vec(&vec, min);
assert_eq!(min_seg_tree.query(4..7), Ok(Some(-5)));
assert_eq!(min_seg_tree.query(0..vec.len()), Ok(Some(-30)));
assert_eq!(min_seg_tree.query(0..2), Ok(Some(-30)));
assert_eq!(min_seg_tree.query(1..3), Ok(Some(-4)));
assert_eq!(min_seg_tree.query(1..7), Ok(Some(-5)));
assert_eq!(min_seg_tree.update(5, 10), Ok(()));
assert_eq!(min_seg_tree.update(14, -8), Ok(()));
assert_eq!(min_seg_tree.query(4..7), Ok(Some(3)));
assert_eq!(
min_seg_tree.update(15, 100),
Err(SegmentTreeError::IndexOutOfBounds)
);
assert_eq!(min_seg_tree.query(5..5), Ok(None));
assert_eq!(
min_seg_tree.query(10..16),
Err(SegmentTreeError::InvalidRange)
);
assert_eq!(
min_seg_tree.query(15..20),
Err(SegmentTreeError::InvalidRange)
);
}
#[test]
fn test_max_segments() {
let vec = vec![1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8];
let mut max_seg_tree = SegmentTree::from_vec(&vec, max);
assert_eq!(max_seg_tree.query(0..vec.len()), Ok(Some(15)));
assert_eq!(max_seg_tree.query(3..5), Ok(Some(7)));
assert_eq!(max_seg_tree.query(4..8), Ok(Some(11)));
assert_eq!(max_seg_tree.query(8..10), Ok(Some(9)));
assert_eq!(max_seg_tree.query(9..12), Ok(Some(15)));
assert_eq!(max_seg_tree.update(4, 10), Ok(()));
assert_eq!(max_seg_tree.update(14, -8), Ok(()));
assert_eq!(max_seg_tree.query(3..5), Ok(Some(10)));
assert_eq!(
max_seg_tree.update(15, 100),
Err(SegmentTreeError::IndexOutOfBounds)
);
assert_eq!(max_seg_tree.query(5..5), Ok(None));
assert_eq!(
max_seg_tree.query(10..16),
Err(SegmentTreeError::InvalidRange)
);
assert_eq!(
max_seg_tree.query(15..20),
Err(SegmentTreeError::InvalidRange)
);
}
#[test]
fn test_sum_segments() {
let vec = vec![1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8];
let mut sum_seg_tree = SegmentTree::from_vec(&vec, |a, b| a + b);
assert_eq!(sum_seg_tree.query(0..vec.len()), Ok(Some(38)));
assert_eq!(sum_seg_tree.query(1..4), Ok(Some(5)));
assert_eq!(sum_seg_tree.query(4..7), Ok(Some(4)));
assert_eq!(sum_seg_tree.query(6..9), Ok(Some(-3)));
assert_eq!(sum_seg_tree.query(9..vec.len()), Ok(Some(37)));
assert_eq!(sum_seg_tree.update(5, 10), Ok(()));
assert_eq!(sum_seg_tree.update(14, -8), Ok(()));
assert_eq!(sum_seg_tree.query(4..7), Ok(Some(19)));
assert_eq!(
sum_seg_tree.update(15, 100),
Err(SegmentTreeError::IndexOutOfBounds)
);
assert_eq!(sum_seg_tree.query(5..5), Ok(None));
assert_eq!(
sum_seg_tree.query(10..16),
Err(SegmentTreeError::InvalidRange)
);
assert_eq!(
sum_seg_tree.query(15..20),
Err(SegmentTreeError::InvalidRange)
);
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/skip_list.rs | src/data_structures/skip_list.rs | use rand::random_range;
use std::{cmp::Ordering, marker::PhantomData, ptr::null_mut};
struct Node<K: Ord, V> {
key: Option<K>,
value: Option<V>,
forward: Vec<*mut Node<K, V>>,
}
impl<K: Ord, V> Node<K, V> {
pub fn new() -> Self {
let mut forward = Vec::with_capacity(4);
forward.resize(4, null_mut());
Node {
key: None,
value: None,
forward,
}
}
pub fn make_node(capacity: usize, key: K, value: V) -> Self {
let mut new_node = Self::new();
new_node.key = Some(key);
new_node.value = Some(value);
new_node.forward = Vec::<*mut Node<K, V>>::with_capacity(capacity);
new_node.forward.resize(capacity, null_mut());
new_node
}
}
/// A probabilistic data structure that maintains a sorted collection of key-value pairs.
///
/// A skip list is a data structure that allows O(log n) search, insertion, and deletion
/// on average by maintaining multiple levels of linked lists with probabilistic balancing.
pub struct SkipList<K: Ord, V> {
header: *mut Node<K, V>,
level: usize,
max_level: usize,
marker: PhantomData<Node<K, V>>,
}
impl<K: Ord, V> SkipList<K, V> {
pub fn new(max_level: usize) -> Self {
let mut node = Box::new(Node::<K, V>::new());
node.forward = Vec::with_capacity(max_level);
node.forward.resize(max_level, null_mut());
SkipList {
header: Box::into_raw(node),
level: 0,
max_level,
marker: PhantomData,
}
}
pub fn search(&self, searched_key: K) -> Option<&V> {
let mut x = self.header;
unsafe {
'outer: for i in (0..self.level).rev() {
loop {
let forward_i = (&*x).forward[i];
if forward_i.is_null() {
continue 'outer;
}
let forward_i_key = (*forward_i).key.as_ref();
match forward_i_key.cmp(&Some(&searched_key)) {
Ordering::Less => {
x = forward_i;
}
_ => {
break;
}
}
}
}
x = (&*x).forward[0];
if x.is_null() {
return None;
}
match (*x).key.as_ref().cmp(&Some(&searched_key)) {
Ordering::Equal => {
return (*x).value.as_ref();
}
_ => {
return None;
}
}
}
}
pub fn insert(&mut self, searched_key: K, new_value: V) -> bool {
let mut update = Vec::<*mut Node<K, V>>::with_capacity(self.max_level);
update.resize(self.max_level, null_mut());
let mut x = self.header;
unsafe {
for i in (0..self.level).rev() {
loop {
let x_forward_i = (&*x).forward[i];
if x_forward_i.is_null() {
break;
}
let x_forward_i_key = (*x_forward_i).key.as_ref();
match x_forward_i_key.cmp(&Some(&searched_key)) {
Ordering::Less => {
x = x_forward_i;
}
_ => {
break;
}
}
}
let update_i = &mut update[i];
*update_i = x;
}
let x_forward_i = (&*x).forward[0];
x = x_forward_i;
if x.is_null() || (*x).key.as_ref().cmp(&Some(&searched_key)) != Ordering::Equal {
let v = random_value(self.max_level);
if v > self.level {
for update_i in update.iter_mut().take(v).skip(self.level) {
*update_i = self.header;
}
self.level = v;
}
let new_node = Node::make_node(v, searched_key, new_value);
x = Box::into_raw(Box::new(new_node));
for (i, t) in update.iter_mut().enumerate().take(self.level) {
let x_forward_i = (&mut *x).forward.get_mut(i);
if x_forward_i.is_none() {
break;
}
let x_forward_i = x_forward_i.unwrap();
let update_i = t;
let update_i_forward_i = &mut (&mut **update_i).forward[i];
*x_forward_i = *update_i_forward_i;
*update_i_forward_i = x;
}
return true;
}
(*x).value.replace(new_value);
return true;
}
}
pub fn delete(&mut self, searched_key: K) -> bool {
let mut update = Vec::<*mut Node<K, V>>::with_capacity(self.max_level);
update.resize(self.max_level, null_mut());
let mut x = self.header;
unsafe {
for i in (0..self.level).rev() {
loop {
let x_forward_i = (&*x).forward[i];
if x_forward_i.is_null() {
break;
}
let x_forward_i_key = (*x_forward_i).key.as_ref();
match x_forward_i_key.cmp(&Some(&searched_key)) {
Ordering::Less => {
x = x_forward_i;
}
_ => {
break;
}
}
}
let update_i = &mut update[i];
*update_i = x;
}
let x_forward_i = *((&*x).forward.first().unwrap());
x = x_forward_i;
if x.is_null() {
return false;
}
match (*x).key.as_ref().cmp(&Some(&searched_key)) {
Ordering::Equal => {
for (i, update_i) in update.iter_mut().enumerate().take(self.level) {
let update_i_forward_i = &mut (&mut **update_i).forward[i];
if update_i_forward_i.is_null() {
break;
}
let x_forward_i = (&mut *x).forward.get_mut(i);
if x_forward_i.is_none() {
break;
}
let x_forward_i = x_forward_i.unwrap();
*update_i_forward_i = *x_forward_i;
}
let _v = Box::from_raw(x);
loop {
if self.level == 0 {
break;
}
let header_forward_level = &(&*self.header).forward[self.level - 1];
if header_forward_level.is_null() {
self.level -= 1;
} else {
break;
}
}
return true;
}
_ => {
return false;
}
}
}
}
pub fn iter(&self) -> Iter<'_, K, V> {
Iter::new(self)
}
}
impl<K: Ord, V> Drop for SkipList<K, V> {
fn drop(&mut self) {
let mut node = unsafe { Box::from_raw(self.header) };
loop {
let node_forward_0 = node.forward.first().unwrap();
if node_forward_0.is_null() {
break;
}
node = unsafe { Box::from_raw(*node_forward_0) };
}
}
}
fn random_value(max: usize) -> usize {
let mut v = 1usize;
loop {
if random_range(1usize..10usize) > 5 && v < max {
v += 1;
} else {
break;
}
}
v
}
pub struct Iter<'a, K: Ord, V> {
current_node: *mut Node<K, V>,
_marker: PhantomData<&'a SkipList<K, V>>,
}
impl<'a, K: Ord, V> Iter<'a, K, V> {
pub fn new(skip_list: &'a SkipList<K, V>) -> Self {
Iter {
current_node: skip_list.header,
_marker: PhantomData,
}
}
}
impl<'a, K: Ord, V> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<Self::Item> {
unsafe {
let forward_0 = (&*self.current_node).forward.first();
forward_0?;
let forward_0 = *forward_0.unwrap();
if forward_0.is_null() {
return None;
}
self.current_node = forward_0;
return match ((*forward_0).key.as_ref(), (*forward_0).value.as_ref()) {
(Some(key), Some(value)) => Some((key, value)),
_ => None,
};
}
}
}
#[cfg(test)]
mod test {
#[test]
fn insert_and_delete() {
let mut skip_list = super::SkipList::<&'static str, i32>::new(8);
skip_list.insert("a", 10);
skip_list.insert("b", 12);
{
let result = skip_list.search("b");
assert!(result.is_some());
assert_eq!(result, Some(&12));
}
{
skip_list.delete("b");
let result = skip_list.search("b");
assert!(result.is_none());
}
skip_list.delete("a");
}
#[test]
fn iterator() {
let mut skip_list = super::SkipList::<&'static str, i32>::new(8);
skip_list.insert("h", 22);
skip_list.insert("a", 12);
skip_list.insert("c", 11);
let result: Vec<(&&'static str, &i32)> = skip_list.iter().collect();
assert_eq!(result, vec![(&"a", &12), (&"c", &11), (&"h", &22)]);
}
#[test]
fn cannot_search() {
let mut skip_list = super::SkipList::<&'static str, i32>::new(8);
{
let result = skip_list.search("h");
assert!(result.is_none());
}
skip_list.insert("h", 10);
{
let result = skip_list.search("a");
assert!(result.is_none());
}
}
#[test]
fn delete_unsuccessfully() {
let mut skip_list = super::SkipList::<&'static str, i32>::new(8);
{
let result = skip_list.delete("a");
assert!(!result);
}
skip_list.insert("a", 10);
{
let result = skip_list.delete("b");
assert!(!result);
}
}
#[test]
fn update_value_with_insert_operation() {
let mut skip_list = super::SkipList::<&'static str, i32>::new(8);
skip_list.insert("a", 10);
{
let result = skip_list.search("a");
assert_eq!(result, Some(&10));
}
skip_list.insert("a", 100);
{
let result = skip_list.search("a");
assert_eq!(result, Some(&100));
}
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/heap.rs | src/data_structures/heap.rs | //! A generic heap data structure.
//!
//! This module provides a `Heap` implementation that can function as either a
//! min-heap or a max-heap. It supports common heap operations such as adding,
//! removing, and iterating over elements. The heap can also be created from
//! an unsorted vector and supports custom comparators for flexible sorting
//! behavior.
use std::{cmp::Ord, slice::Iter};
/// A heap data structure that can be used as a min-heap, max-heap or with
/// custom comparators.
///
/// This struct manages a collection of items where the heap property is maintained.
/// The heap can be configured to order elements based on a provided comparator function,
/// allowing for both min-heap and max-heap functionalities, as well as custom sorting orders.
pub struct Heap<T> {
items: Vec<T>,
comparator: fn(&T, &T) -> bool,
}
impl<T> Heap<T> {
/// Creates a new, empty heap with a custom comparator function.
///
/// # Parameters
/// - `comparator`: A function that defines the heap's ordering.
///
/// # Returns
/// A new `Heap` instance.
pub fn new(comparator: fn(&T, &T) -> bool) -> Self {
Self {
items: vec![],
comparator,
}
}
/// Creates a heap from a vector and a custom comparator function.
///
/// # Parameters
/// - `items`: A vector of items to be turned into a heap.
/// - `comparator`: A function that defines the heap's ordering.
///
/// # Returns
/// A `Heap` instance with the elements from the provided vector.
pub fn from_vec(items: Vec<T>, comparator: fn(&T, &T) -> bool) -> Self {
let mut heap = Self { items, comparator };
heap.build_heap();
heap
}
/// Constructs the heap from an unsorted vector by applying the heapify process.
fn build_heap(&mut self) {
let last_parent_idx = (self.len() / 2).wrapping_sub(1);
for idx in (0..=last_parent_idx).rev() {
self.heapify_down(idx);
}
}
/// Returns the number of elements in the heap.
///
/// # Returns
/// The number of elements in the heap.
pub fn len(&self) -> usize {
self.items.len()
}
/// Checks if the heap is empty.
///
/// # Returns
/// `true` if the heap is empty, `false` otherwise.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Adds a new element to the heap and maintains the heap property.
///
/// # Parameters
/// - `value`: The value to add to the heap.
pub fn add(&mut self, value: T) {
self.items.push(value);
self.heapify_up(self.len() - 1);
}
/// Removes and returns the root element from the heap.
///
/// # Returns
/// The root element if the heap is not empty, otherwise `None`.
pub fn pop(&mut self) -> Option<T> {
if self.is_empty() {
return None;
}
let next = Some(self.items.swap_remove(0));
if !self.is_empty() {
self.heapify_down(0);
}
next
}
/// Returns an iterator over the elements in the heap.
///
/// # Returns
/// An iterator over the elements in the heap, in their internal order.
pub fn iter(&self) -> Iter<'_, T> {
self.items.iter()
}
/// Moves an element upwards to restore the heap property.
///
/// # Parameters
/// - `idx`: The index of the element to heapify up.
fn heapify_up(&mut self, mut idx: usize) {
while let Some(pdx) = self.parent_idx(idx) {
if (self.comparator)(&self.items[idx], &self.items[pdx]) {
self.items.swap(idx, pdx);
idx = pdx;
} else {
break;
}
}
}
/// Moves an element downwards to restore the heap property.
///
/// # Parameters
/// - `idx`: The index of the element to heapify down.
fn heapify_down(&mut self, mut idx: usize) {
while self.children_present(idx) {
let cdx = {
if self.right_child_idx(idx) >= self.len() {
self.left_child_idx(idx)
} else {
let ldx = self.left_child_idx(idx);
let rdx = self.right_child_idx(idx);
if (self.comparator)(&self.items[ldx], &self.items[rdx]) {
ldx
} else {
rdx
}
}
};
if (self.comparator)(&self.items[cdx], &self.items[idx]) {
self.items.swap(idx, cdx);
idx = cdx;
} else {
break;
}
}
}
/// Returns the index of the parent of the element at `idx`.
///
/// # Parameters
/// - `idx`: The index of the element.
///
/// # Returns
/// The index of the parent element if it exists, otherwise `None`.
fn parent_idx(&self, idx: usize) -> Option<usize> {
if idx > 0 {
Some((idx - 1) / 2)
} else {
None
}
}
/// Checks if the element at `idx` has children.
///
/// # Parameters
/// - `idx`: The index of the element.
///
/// # Returns
/// `true` if the element has children, `false` otherwise.
fn children_present(&self, idx: usize) -> bool {
self.left_child_idx(idx) < self.len()
}
/// Returns the index of the left child of the element at `idx`.
///
/// # Parameters
/// - `idx`: The index of the element.
///
/// # Returns
/// The index of the left child.
fn left_child_idx(&self, idx: usize) -> usize {
idx * 2 + 1
}
/// Returns the index of the right child of the element at `idx`.
///
/// # Parameters
/// - `idx`: The index of the element.
///
/// # Returns
/// The index of the right child.
fn right_child_idx(&self, idx: usize) -> usize {
self.left_child_idx(idx) + 1
}
}
impl<T> Heap<T>
where
T: Ord,
{
/// Creates a new min-heap.
///
/// # Returns
/// A new `Heap` instance configured as a min-heap.
pub fn new_min() -> Heap<T> {
Self::new(|a, b| a < b)
}
/// Creates a new max-heap.
///
/// # Returns
/// A new `Heap` instance configured as a max-heap.
pub fn new_max() -> Heap<T> {
Self::new(|a, b| a > b)
}
/// Creates a min-heap from an unsorted vector.
///
/// # Parameters
/// - `items`: A vector of items to be turned into a min-heap.
///
/// # Returns
/// A `Heap` instance configured as a min-heap.
pub fn from_vec_min(items: Vec<T>) -> Heap<T> {
Self::from_vec(items, |a, b| a < b)
}
/// Creates a max-heap from an unsorted vector.
///
/// # Parameters
/// - `items`: A vector of items to be turned into a max-heap.
///
/// # Returns
/// A `Heap` instance configured as a max-heap.
pub fn from_vec_max(items: Vec<T>) -> Heap<T> {
Self::from_vec(items, |a, b| a > b)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_empty_heap() {
let mut heap: Heap<i32> = Heap::new_max();
assert_eq!(heap.pop(), None);
}
#[test]
fn test_min_heap() {
let mut heap = Heap::new_min();
heap.add(4);
heap.add(2);
heap.add(9);
heap.add(11);
assert_eq!(heap.len(), 4);
assert_eq!(heap.pop(), Some(2));
assert_eq!(heap.pop(), Some(4));
assert_eq!(heap.pop(), Some(9));
heap.add(1);
assert_eq!(heap.pop(), Some(1));
assert_eq!(heap.pop(), Some(11));
assert_eq!(heap.pop(), None);
}
#[test]
fn test_max_heap() {
let mut heap = Heap::new_max();
heap.add(4);
heap.add(2);
heap.add(9);
heap.add(11);
assert_eq!(heap.len(), 4);
assert_eq!(heap.pop(), Some(11));
assert_eq!(heap.pop(), Some(9));
assert_eq!(heap.pop(), Some(4));
heap.add(1);
assert_eq!(heap.pop(), Some(2));
assert_eq!(heap.pop(), Some(1));
assert_eq!(heap.pop(), None);
}
#[test]
fn test_iter_heap() {
let mut heap = Heap::new_min();
heap.add(4);
heap.add(2);
heap.add(9);
heap.add(11);
let mut iter = heap.iter();
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&4));
assert_eq!(iter.next(), Some(&9));
assert_eq!(iter.next(), Some(&11));
assert_eq!(iter.next(), None);
assert_eq!(heap.len(), 4);
assert_eq!(heap.pop(), Some(2));
assert_eq!(heap.pop(), Some(4));
assert_eq!(heap.pop(), Some(9));
assert_eq!(heap.pop(), Some(11));
assert_eq!(heap.pop(), None);
}
#[test]
fn test_from_vec_min() {
let vec = vec![3, 1, 4, 1, 5, 9, 2, 6, 5];
let mut heap = Heap::from_vec_min(vec);
assert_eq!(heap.len(), 9);
assert_eq!(heap.pop(), Some(1));
assert_eq!(heap.pop(), Some(1));
assert_eq!(heap.pop(), Some(2));
heap.add(0);
assert_eq!(heap.pop(), Some(0));
}
#[test]
fn test_from_vec_max() {
let vec = vec![3, 1, 4, 1, 5, 9, 2, 6, 5];
let mut heap = Heap::from_vec_max(vec);
assert_eq!(heap.len(), 9);
assert_eq!(heap.pop(), Some(9));
assert_eq!(heap.pop(), Some(6));
assert_eq!(heap.pop(), Some(5));
heap.add(10);
assert_eq!(heap.pop(), Some(10));
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/probabilistic/mod.rs | src/data_structures/probabilistic/mod.rs | pub mod bloom_filter;
pub mod count_min_sketch;
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/probabilistic/bloom_filter.rs | src/data_structures/probabilistic/bloom_filter.rs | use std::collections::hash_map::{DefaultHasher, RandomState};
use std::hash::{BuildHasher, Hash, Hasher};
/// A Bloom Filter <https://en.wikipedia.org/wiki/Bloom_filter> is a probabilistic data structure testing whether an element belongs to a set or not
/// Therefore, its contract looks very close to the one of a set, for example a `HashSet`
pub trait BloomFilter<Item: Hash> {
fn insert(&mut self, item: Item);
fn contains(&self, item: &Item) -> bool;
}
/// What is the point of using a Bloom Filter if it acts like a Set?
/// Let's imagine we have a huge number of elements to store (like un unbounded data stream) a Set storing every element will most likely take up too much space, at some point.
/// As other probabilistic data structures like Count-min Sketch, the goal of a Bloom Filter is to trade off exactitude for constant space.
/// We won't have a strictly exact result of whether the value belongs to the set, but we'll use constant space instead
/// Let's start with the basic idea behind the implementation
/// Let's start by trying to make a `HashSet` with constant space:
/// Instead of storing every element and grow the set infinitely, let's use a vector with constant capacity `CAPACITY`
/// Each element of this vector will be a boolean.
/// When a new element is inserted, we hash its value and set the index at index `hash(item) % CAPACITY` to `true`
/// When looking for an item, we hash its value and retrieve the boolean at index `hash(item) % CAPACITY`
/// If it's `false` it's absolutely sure the item isn't present
/// If it's `true` the item may be present, or maybe another one produces the same hash
#[allow(dead_code)]
#[derive(Debug)]
struct BasicBloomFilter<const CAPACITY: usize> {
vec: [bool; CAPACITY],
}
impl<const CAPACITY: usize> Default for BasicBloomFilter<CAPACITY> {
fn default() -> Self {
Self {
vec: [false; CAPACITY],
}
}
}
impl<Item: Hash, const CAPACITY: usize> BloomFilter<Item> for BasicBloomFilter<CAPACITY> {
fn insert(&mut self, item: Item) {
let mut hasher = DefaultHasher::new();
item.hash(&mut hasher);
let idx = (hasher.finish() % CAPACITY as u64) as usize;
self.vec[idx] = true;
}
fn contains(&self, item: &Item) -> bool {
let mut hasher = DefaultHasher::new();
item.hash(&mut hasher);
let idx = (hasher.finish() % CAPACITY as u64) as usize;
self.vec[idx]
}
}
/// Can we improve it? Certainly, in different ways.
/// One pattern you may have identified here is that we use a "binary array" (a vector of binary values)
/// For instance, we might have `[0,1,0,0,1,0]`, which is actually the binary representation of 9
/// This means we can immediately replace our `Vec<bool>` by an actual number
/// What would it mean to set a `1` at index `i`?
/// Imagine a `CAPACITY` of `6`. The initial value for our mask is `000000`.
/// We want to store `"Bloom"`. Its hash modulo `CAPACITY` is `5`. Which means we need to set `1` at the last index.
/// It can be performed by doing `000000 | 000001`
/// Meaning we can hash the item value, use a modulo to find the index, and do a binary `or` between the current number and the index
#[allow(dead_code)]
#[derive(Debug, Default)]
struct SingleBinaryBloomFilter {
fingerprint: u128, // let's use 128 bits, the equivalent of using CAPACITY=128 in the previous example
}
/// Given a value and a hash function, compute the hash and return the bit mask
fn mask_128<T: Hash>(hasher: &mut DefaultHasher, item: T) -> u128 {
item.hash(hasher);
let idx = (hasher.finish() % 128) as u32;
// idx is where we want to put a 1, let's convert this into a proper binary mask
2_u128.pow(idx)
}
impl<T: Hash> BloomFilter<T> for SingleBinaryBloomFilter {
fn insert(&mut self, item: T) {
self.fingerprint |= mask_128(&mut DefaultHasher::new(), &item);
}
fn contains(&self, item: &T) -> bool {
(self.fingerprint & mask_128(&mut DefaultHasher::new(), item)) > 0
}
}
/// We may have made some progress in term of CPU efficiency, using binary operators.
/// But we might still run into a lot of collisions with a single 128-bits number.
/// Can we use greater numbers then? Currently, our implementation is limited to 128 bits.
///
/// Should we go back to using an array, then?
/// We could! But instead of using `Vec<bool>` we could use `Vec<u8>`.
/// Each `u8` can act as a mask as we've done before, and is actually 1 byte in memory (same as a boolean!)
/// That'd allow us to go over 128 bits, but would divide by 8 the memory footprint.
/// That's one thing, and will involve dividing / shifting by 8 in different places.
///
/// But still, can we reduce the collisions furthermore?
///
/// As we did with count-min-sketch, we could use multiple hash function.
/// When inserting a value, we compute its hash with every hash function (`hash_i`) and perform the same operation as above (the OR with `fingerprint`)
/// Then when looking for a value, if **ANY** of the tests (`hash` then `AND`) returns 0 then this means the value is missing from the set, otherwise it would have returned 1
/// If it returns `1`, it **may** be that the item is present, but could also be a collision
/// This is what a Bloom Filter is about: returning `false` means the value is necessarily absent, and returning true means it may be present
pub struct MultiBinaryBloomFilter {
filter_size: usize,
bytes: Vec<u8>,
hash_builders: Vec<RandomState>,
}
impl MultiBinaryBloomFilter {
pub fn with_dimensions(filter_size: usize, hash_count: usize) -> Self {
let bytes_count = filter_size / 8 + usize::from(!filter_size.is_multiple_of(8)); // we need 8 times less entries in the array, since we are using bytes. Careful that we have at least one element though
Self {
filter_size,
bytes: vec![0; bytes_count],
hash_builders: vec![RandomState::new(); hash_count],
}
}
pub fn from_estimate(
estimated_count_of_items: usize,
max_false_positive_probability: f64,
) -> Self {
// Check Wikipedia for these formulae
let optimal_filter_size = (-(estimated_count_of_items as f64)
* max_false_positive_probability.ln()
/ (2.0_f64.ln().powi(2)))
.ceil() as usize;
let optimal_hash_count = ((optimal_filter_size as f64 / estimated_count_of_items as f64)
* 2.0_f64.ln())
.ceil() as usize;
Self::with_dimensions(optimal_filter_size, optimal_hash_count)
}
}
impl<Item: Hash> BloomFilter<Item> for MultiBinaryBloomFilter {
fn insert(&mut self, item: Item) {
for builder in &self.hash_builders {
let mut hasher = builder.build_hasher();
item.hash(&mut hasher);
let hash = builder.hash_one(&item);
let index = hash % self.filter_size as u64;
let byte_index = index as usize / 8; // this is this byte that we need to modify
let bit_index = (index % 8) as u8; // we cannot only OR with value 1 this time, since we have 8 bits
self.bytes[byte_index] |= 1 << bit_index;
}
}
fn contains(&self, item: &Item) -> bool {
for builder in &self.hash_builders {
let mut hasher = builder.build_hasher();
item.hash(&mut hasher);
let hash = builder.hash_one(item);
let index = hash % self.filter_size as u64;
let byte_index = index as usize / 8; // this is this byte that we need to modify
let bit_index = (index % 8) as u8; // we cannot only OR with value 1 this time, since we have 8 bits
if self.bytes[byte_index] & (1 << bit_index) == 0 {
return false;
}
}
true
}
}
#[cfg(test)]
mod tests {
use crate::data_structures::probabilistic::bloom_filter::{
BasicBloomFilter, BloomFilter, MultiBinaryBloomFilter, SingleBinaryBloomFilter,
};
use quickcheck::{Arbitrary, Gen};
use quickcheck_macros::quickcheck;
use std::collections::HashSet;
#[derive(Debug, Clone)]
struct TestSet {
to_insert: HashSet<i32>,
to_test: Vec<i32>,
}
impl Arbitrary for TestSet {
fn arbitrary(g: &mut Gen) -> Self {
let mut qty = usize::arbitrary(g) % 5_000;
if qty < 50 {
qty += 50; // won't be perfectly uniformly distributed
}
let mut to_insert = HashSet::with_capacity(qty);
let mut to_test = Vec::with_capacity(qty);
for _ in 0..(qty) {
to_insert.insert(i32::arbitrary(g));
to_test.push(i32::arbitrary(g));
}
TestSet { to_insert, to_test }
}
}
#[quickcheck]
fn basic_filter_must_not_return_false_negative(TestSet { to_insert, to_test }: TestSet) {
let mut basic_filter = BasicBloomFilter::<10_000>::default();
for item in &to_insert {
basic_filter.insert(*item);
}
for other in to_test {
if !basic_filter.contains(&other) {
assert!(!to_insert.contains(&other))
}
}
}
#[quickcheck]
fn binary_filter_must_not_return_false_negative(TestSet { to_insert, to_test }: TestSet) {
let mut binary_filter = SingleBinaryBloomFilter::default();
for item in &to_insert {
binary_filter.insert(*item);
}
for other in to_test {
if !binary_filter.contains(&other) {
assert!(!to_insert.contains(&other))
}
}
}
#[quickcheck]
fn a_basic_filter_of_capacity_128_is_the_same_as_a_binary_filter(
TestSet { to_insert, to_test }: TestSet,
) {
let mut basic_filter = BasicBloomFilter::<128>::default(); // change 32 to anything else here, and the test won't pass
let mut binary_filter = SingleBinaryBloomFilter::default();
for item in &to_insert {
basic_filter.insert(*item);
binary_filter.insert(*item);
}
for other in to_test {
// Since we use the same DefaultHasher::new(), and both have size 32, we should have exactly the same results
assert_eq!(
basic_filter.contains(&other),
binary_filter.contains(&other)
);
}
}
const FALSE_POSITIVE_MAX: f64 = 0.05;
#[quickcheck]
fn a_multi_binary_bloom_filter_must_not_return_false_negatives(
TestSet { to_insert, to_test }: TestSet,
) {
let n = to_insert.len();
if n == 0 {
// avoid dividing by 0 when adjusting the size
return;
}
// See Wikipedia for those formula
let mut binary_filter = MultiBinaryBloomFilter::from_estimate(n, FALSE_POSITIVE_MAX);
for item in &to_insert {
binary_filter.insert(*item);
}
let tests = to_test.len();
let mut false_positives = 0;
for other in to_test {
if !binary_filter.contains(&other) {
assert!(!to_insert.contains(&other))
} else if !to_insert.contains(&other) {
// false positive
false_positives += 1;
}
}
let fp_rate = false_positives as f64 / tests as f64;
assert!(fp_rate < 1.0); // This isn't really a test, but so that you have the `fp_rate` variable to print out, or evaluate
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/data_structures/probabilistic/count_min_sketch.rs | src/data_structures/probabilistic/count_min_sketch.rs | use std::collections::hash_map::RandomState;
use std::fmt::{Debug, Formatter};
use std::hash::{BuildHasher, Hash};
/// A probabilistic data structure holding an approximate count for diverse items efficiently (using constant space)
///
/// Let's imagine we want to count items from an incoming (unbounded) data stream
/// One way to do this would be to hold a frequency hashmap, counting element hashes
/// This works extremely well, but unfortunately would require a lot of memory if we have a huge diversity of incoming items in the data stream
///
/// CountMinSketch aims at solving this problem, trading off the exact count for an approximate one, but getting from potentially unbounded space complexity to constant complexity
/// See the implementation below for more details
///
/// Here is the definition of the different allowed operations on a CountMinSketch:
/// * increment the count of an item
/// * retrieve the count of an item
pub trait CountMinSketch {
type Item;
fn increment(&mut self, item: Self::Item);
fn increment_by(&mut self, item: Self::Item, count: usize);
fn get_count(&self, item: Self::Item) -> usize;
}
/// The common implementation of a CountMinSketch
/// Holding a DEPTH x WIDTH matrix of counts
///
/// The idea behind the implementation is the following:
/// Let's start from our problem statement above. We have a frequency map of counts, and want to go reduce its space complexity
/// The immediate way to do this would be to use a Vector with a fixed size, let this size be `WIDTH`
/// We will be holding the count of each item `item` in the Vector, at index `i = hash(item) % WIDTH` where `hash` is a hash function: `item -> usize`
/// We now have constant space.
///
/// The problem though is that we'll potentially run into a lot of collisions.
/// Taking an extreme example, if `WIDTH = 1`, all items will have the same count, which is the sum of counts of every items
/// We could reduce the amount of collisions by using a bigger `WIDTH` but this wouldn't be way more efficient than the "big" frequency map
/// How do we improve the solution, but still keeping constant space?
///
/// The idea is to use not just one vector, but multiple (`DEPTH`) ones and attach different `hash` functions to each vector
/// This would lead to the following data structure:
/// <- WIDTH = 5 ->
/// D hash1: [0, 0, 0, 0, 0]
/// E hash2: [0, 0, 0, 0, 0]
/// P hash3: [0, 0, 0, 0, 0]
/// T hash4: [0, 0, 0, 0, 0]
/// H hash5: [0, 0, 0, 0, 0]
/// = hash6: [0, 0, 0, 0, 0]
/// 7 hash7: [0, 0, 0, 0, 0]
/// Every hash function must return a different value for the same item.
/// Let's say we hash "TEST" and:
/// hash1("TEST") = 42 => idx = 2
/// hash2("TEST") = 26 => idx = 1
/// hash3("TEST") = 10 => idx = 0
/// hash4("TEST") = 33 => idx = 3
/// hash5("TEST") = 54 => idx = 4
/// hash6("TEST") = 11 => idx = 1
/// hash7("TEST") = 50 => idx = 0
/// This would lead our structure to become:
/// <- WIDTH = 5 ->
/// D hash1: [0, 0, 1, 0, 0]
/// E hash2: [0, 1, 0, 0, 0]
/// P hash3: [1, 0, 0, 0, 0]
/// T hash4: [0, 0, 0, 1, 0]
/// H hash5: [0, 0, 0, 0, 1]
/// = hash6: [0, 1, 0, 0, 0]
/// 7 hash7: [1, 0, 0, 0, 0]
///
/// Now say we hash "OTHER" and:
/// hash1("OTHER") = 23 => idx = 3
/// hash2("OTHER") = 11 => idx = 1
/// hash3("OTHER") = 52 => idx = 2
/// hash4("OTHER") = 25 => idx = 0
/// hash5("OTHER") = 31 => idx = 1
/// hash6("OTHER") = 24 => idx = 4
/// hash7("OTHER") = 30 => idx = 0
/// Leading our data structure to become:
/// <- WIDTH = 5 ->
/// D hash1: [0, 0, 1, 1, 0]
/// E hash2: [0, 2, 0, 0, 0]
/// P hash3: [1, 0, 1, 0, 0]
/// T hash4: [1, 0, 0, 1, 0]
/// H hash5: [0, 1, 0, 0, 1]
/// = hash6: [0, 1, 0, 0, 1]
/// 7 hash7: [2, 0, 0, 0, 0]
///
/// We actually can witness some collisions (invalid counts of `2` above in some rows).
/// This means that if we have to return the count for "TEST", we'd actually fetch counts from every row and return the minimum value
///
/// This could potentially be overestimated if we have a huge number of entries and a lot of collisions.
/// But an interesting property is that the count we return for "TEST" cannot be underestimated
pub struct HashCountMinSketch<Item: Hash, const WIDTH: usize, const DEPTH: usize> {
phantom: std::marker::PhantomData<Item>, // just a marker for Item to be used
counts: [[usize; WIDTH]; DEPTH],
hashers: [RandomState; DEPTH],
}
impl<Item: Hash, const WIDTH: usize, const DEPTH: usize> Debug
for HashCountMinSketch<Item, WIDTH, DEPTH>
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Item").field("vecs", &self.counts).finish()
}
}
impl<T: Hash, const WIDTH: usize, const DEPTH: usize> Default
for HashCountMinSketch<T, WIDTH, DEPTH>
{
fn default() -> Self {
let hashers = std::array::from_fn(|_| RandomState::new());
Self {
phantom: std::marker::PhantomData,
counts: [[0; WIDTH]; DEPTH],
hashers,
}
}
}
impl<Item: Hash, const WIDTH: usize, const DEPTH: usize> CountMinSketch
for HashCountMinSketch<Item, WIDTH, DEPTH>
{
type Item = Item;
fn increment(&mut self, item: Self::Item) {
self.increment_by(item, 1)
}
fn increment_by(&mut self, item: Self::Item, count: usize) {
for (row, r) in self.hashers.iter_mut().enumerate() {
let mut h = r.build_hasher();
item.hash(&mut h);
let hashed = r.hash_one(&item);
let col = (hashed % WIDTH as u64) as usize;
self.counts[row][col] += count;
}
}
fn get_count(&self, item: Self::Item) -> usize {
self.hashers
.iter()
.enumerate()
.map(|(row, r)| {
let mut h = r.build_hasher();
item.hash(&mut h);
let hashed = r.hash_one(&item);
let col = (hashed % WIDTH as u64) as usize;
self.counts[row][col]
})
.min()
.unwrap()
}
}
#[cfg(test)]
mod tests {
use crate::data_structures::probabilistic::count_min_sketch::{
CountMinSketch, HashCountMinSketch,
};
use quickcheck::{Arbitrary, Gen};
use std::collections::HashSet;
#[test]
fn hash_functions_should_hash_differently() {
let mut sketch: HashCountMinSketch<&str, 50, 50> = HashCountMinSketch::default(); // use a big DEPTH
sketch.increment("something");
// We want to check that our hash functions actually produce different results, so we'll store the indices where we encounter a count=1 in a set
let mut indices_of_ones: HashSet<usize> = HashSet::default();
for counts in sketch.counts {
let ones = counts
.into_iter()
.enumerate()
.filter_map(|(idx, count)| (count == 1).then_some(idx))
.collect::<Vec<_>>();
assert_eq!(1, ones.len());
indices_of_ones.insert(ones[0]);
}
// Given the parameters (WIDTH = 50, DEPTH = 50) it's extremely unlikely that all hash functions hash to the same index
assert!(indices_of_ones.len() > 1); // but we want to avoid a bug where all hash functions would produce the same hash (or hash to the same index)
}
#[test]
fn inspect_counts() {
let mut sketch: HashCountMinSketch<&str, 5, 7> = HashCountMinSketch::default();
sketch.increment("test");
// Inspect internal state:
for counts in sketch.counts {
let zeroes = counts.iter().filter(|count| **count == 0).count();
assert_eq!(4, zeroes);
let ones = counts.iter().filter(|count| **count == 1).count();
assert_eq!(1, ones);
}
sketch.increment("test");
for counts in sketch.counts {
let zeroes = counts.iter().filter(|count| **count == 0).count();
assert_eq!(4, zeroes);
let twos = counts.iter().filter(|count| **count == 2).count();
assert_eq!(1, twos);
}
// This one is actually deterministic
assert_eq!(2, sketch.get_count("test"));
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
struct TestItem {
item: String,
count: usize,
}
const MAX_STR_LEN: u8 = 30;
const MAX_COUNT: usize = 20;
impl Arbitrary for TestItem {
fn arbitrary(g: &mut Gen) -> Self {
let str_len = u8::arbitrary(g) % MAX_STR_LEN;
let mut str = String::with_capacity(str_len as usize);
for _ in 0..str_len {
str.push(char::arbitrary(g));
}
let count = usize::arbitrary(g) % MAX_COUNT;
TestItem { item: str, count }
}
}
#[quickcheck_macros::quickcheck]
fn must_not_understimate_count(test_items: Vec<TestItem>) {
let test_items = test_items.into_iter().collect::<HashSet<_>>(); // remove duplicated (would lead to weird counts)
let n = test_items.len();
let mut sketch: HashCountMinSketch<String, 50, 10> = HashCountMinSketch::default();
let mut exact_count = 0;
for TestItem { item, count } in &test_items {
sketch.increment_by(item.clone(), *count);
}
for TestItem { item, count } in test_items {
let stored_count = sketch.get_count(item);
assert!(stored_count >= count);
if count == stored_count {
exact_count += 1;
}
}
if n > 20 {
// if n is too short, the stat isn't really relevant
let exact_ratio = exact_count as f64 / n as f64;
assert!(exact_ratio > 0.7); // the proof is quite hard, but this should be OK
}
}
}
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.