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/conversions/length_conversion.rs | src/conversions/length_conversion.rs | /// Author : https://github.com/ali77gh
/// Conversion of length units.
///
/// Available Units:
/// -> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter
/// -> Wikipedia reference: https://en.wikipedia.org/wiki/Centimeter
/// -> Wikipedia reference: https://en.wikipedia.org/wiki/Meter
/// -> Wikipedia refe... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/hexadecimal_to_octal.rs | src/conversions/hexadecimal_to_octal.rs | // Author: NithinU2802
// Hexadecimal to Octal Converter: Converts Hexadecimal to Octal
// Wikipedia References:
// 1. https://en.wikipedia.org/wiki/Hexadecimal
// 2. https://en.wikipedia.org/wiki/Octal
pub fn hexadecimal_to_octal(hex_str: &str) -> Result<String, &'static str> {
let hex_str = hex_str.trim();
... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/octal_to_binary.rs | src/conversions/octal_to_binary.rs | // Author : cyrixninja
// Octal to Binary Converter : Converts Octal to Binary
// Wikipedia References : 1. https://en.wikipedia.org/wiki/Octal
// 2. https://en.wikipedia.org/wiki/Binary_number
pub fn octal_to_binary(octal_str: &str) -> Result<String, &'static str> {
let octal_str = octal_... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/binary_to_octal.rs | src/conversions/binary_to_octal.rs | // Author: NithinU2802
// Binary to Octal Converter: Converts Binary to Octal
// Wikipedia References:
// 1. https://en.wikipedia.org/wiki/Binary_number
// 2. https://en.wikipedia.org/wiki/Octal
pub fn binary_to_octal(binary_str: &str) -> Result<String, &'static str> {
// Validate input
let binary_str = binary... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/hexadecimal_to_decimal.rs | src/conversions/hexadecimal_to_decimal.rs | pub fn hexadecimal_to_decimal(hexadecimal_str: &str) -> Result<u64, &'static str> {
if hexadecimal_str.is_empty() {
return Err("Empty input");
}
for hexadecimal_str in hexadecimal_str.chars() {
if !hexadecimal_str.is_ascii_hexdigit() {
return Err("Input was not a hexadecimal num... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/rgb_cmyk_conversion.rs | src/conversions/rgb_cmyk_conversion.rs | /// Author : https://github.com/ali77gh\
/// References:\
/// RGB: https://en.wikipedia.org/wiki/RGB_color_model\
/// CMYK: https://en.wikipedia.org/wiki/CMYK_color_model\
/// This function Converts RGB to CMYK format
///
/// ### Params
/// * `r` - red
/// * `g` - green
/// * `b` - blue
///
/// ### Returns
/// (C, M,... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/mod.rs | src/conversions/mod.rs | mod binary_to_decimal;
mod binary_to_hexadecimal;
mod binary_to_octal;
mod decimal_to_binary;
mod decimal_to_hexadecimal;
mod decimal_to_octal;
mod hexadecimal_to_binary;
mod hexadecimal_to_decimal;
mod hexadecimal_to_octal;
mod length_conversion;
mod octal_to_binary;
mod octal_to_decimal;
mod octal_to_hexadecimal;
mod... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/hexadecimal_to_binary.rs | src/conversions/hexadecimal_to_binary.rs | // Author : cyrixninja
// Hexadecimal to Binary Converter : Converts Hexadecimal to Binary
// Wikipedia References : 1. https://en.wikipedia.org/wiki/Hexadecimal
// 2. https://en.wikipedia.org/wiki/Binary_number
// Other References for Testing : https://www.rapidtables.com/convert/number/hex-to... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/decimal_to_binary.rs | src/conversions/decimal_to_binary.rs | pub fn decimal_to_binary(base_num: u64) -> String {
let mut num = base_num;
let mut binary_num = String::new();
loop {
let bit = (num % 2).to_string();
binary_num.push_str(&bit);
num /= 2;
if num == 0 {
break;
}
}
let bits = binary_num.chars();
... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/octal_to_decimal.rs | src/conversions/octal_to_decimal.rs | // Author: cyrixninja
// Octal to Decimal Converter: Converts Octal to Decimal
// Wikipedia References:
// 1. https://en.wikipedia.org/wiki/Octal
// 2. https://en.wikipedia.org/wiki/Decimal
pub fn octal_to_decimal(octal_str: &str) -> Result<u64, &'static str> {
let octal_str = octal_str.trim();
if octal_str.i... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/decimal_to_hexadecimal.rs | src/conversions/decimal_to_hexadecimal.rs | pub fn decimal_to_hexadecimal(base_num: u64) -> String {
let mut num = base_num;
let mut hexadecimal_num = String::new();
loop {
let remainder = num % 16;
let hex_char = if remainder < 10 {
(remainder as u8 + b'0') as char
} else {
(remainder as u8 - 10 + b'A... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/find_unique_number.rs | src/bit_manipulation/find_unique_number.rs | /// Finds the unique number in a slice where every other element appears twice.
///
/// This function uses the XOR bitwise operation. Since XOR has the property that
/// `a ^ a = 0` and `a ^ 0 = a`, all paired numbers cancel out, leaving only the
/// unique number.
///
/// # Arguments
///
/// * `arr` - A slice of integ... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/find_previous_power_of_two.rs | src/bit_manipulation/find_previous_power_of_two.rs | //! Previous Power of Two
//!
//! This module provides a function to find the largest power of two that is less than
//! or equal to a given non-negative integer.
//!
//! # Algorithm
//!
//! The algorithm works by repeatedly left-shifting (doubling) a power value starting
//! from 1 until it exceeds the input number, t... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/highest_set_bit.rs | src/bit_manipulation/highest_set_bit.rs | //! This module provides a function to find the position of the most significant bit (MSB)
//! set to 1 in a given positive integer.
/// Finds the position of the highest (most significant) set bit in a positive integer.
///
/// # Arguments
///
/// * `num` - An integer value for which the highest set bit will be deter... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/n_bits_gray_code.rs | src/bit_manipulation/n_bits_gray_code.rs | /// Custom error type for Gray code generation.
#[derive(Debug, PartialEq)]
pub enum GrayCodeError {
ZeroBitCount,
}
/// Generates an n-bit Gray code sequence using the direct Gray code formula.
///
/// # Arguments
///
/// * `n` - The number of bits for the Gray code.
///
/// # Returns
///
/// A vector of Gray cod... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/rightmost_set_bit.rs | src/bit_manipulation/rightmost_set_bit.rs | /// Finds the index (position) of the rightmost set bit in a number.
///
/// The index is 1-based, where position 1 is the least significant bit (rightmost).
/// This function uses the bitwise trick `n & -n` to isolate the rightmost set bit,
/// then calculates its position using logarithm base 2.
///
/// # Algorithm
/... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/counting_bits.rs | src/bit_manipulation/counting_bits.rs | //! This module implements a function to count the number of set bits (1s)
//! in the binary representation of an unsigned integer.
//! It uses Brian Kernighan's algorithm, which efficiently clears the least significant
//! set bit in each iteration until all bits are cleared.
//! The algorithm runs in O(k), where k is... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/find_missing_number.rs | src/bit_manipulation/find_missing_number.rs | /// Finds the missing number in a slice of consecutive integers.
///
/// This function uses XOR bitwise operation to find the missing number.
/// It XORs all expected numbers in the range [min, max] with the actual
/// numbers present in the array. Since XOR has the property that `a ^ a = 0`,
/// all present numbers ca... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/twos_complement.rs | src/bit_manipulation/twos_complement.rs | //! Two's Complement Representation
//!
//! Two's complement is a mathematical operation on binary numbers and a binary signed
//! number representation. It is widely used in computing as the most common method of
//! representing signed integers on computers.
//!
//! For more information: <https://en.wikipedia.org/wik... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/reverse_bits.rs | src/bit_manipulation/reverse_bits.rs | //! This module provides a function to reverse the bits of a 32-bit unsigned integer.
//!
//! The algorithm works by iterating through each of the 32 bits from least
//! significant to most significant, extracting each bit and placing it in the
//! reverse position.
//!
//! # Algorithm
//!
//! For each of the 32 bits:
... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/swap_odd_even_bits.rs | src/bit_manipulation/swap_odd_even_bits.rs | /// Swaps odd and even bits in an integer.
///
/// This function separates the even bits (0, 2, 4, 6, etc.) and odd bits (1, 3, 5, 7, etc.)
/// using bitwise AND operations, then swaps them by shifting and combining with OR.
///
/// # Arguments
///
/// * `num` - A 32-bit unsigned integer
///
/// # Returns
///
/// A new... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/binary_count_trailing_zeros.rs | src/bit_manipulation/binary_count_trailing_zeros.rs | /// Counts the number of trailing zeros in the binary representation of a number
///
/// # Arguments
///
/// * `num` - The input number
///
/// # Returns
///
/// The number of trailing zeros in the binary representation
///
/// # Examples
///
/// ```
/// use the_algorithms_rust::bit_manipulation::binary_count_trailing_... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/binary_coded_decimal.rs | src/bit_manipulation/binary_coded_decimal.rs | //! Binary Coded Decimal (BCD) conversion
//!
//! This module provides a function to convert decimal integers to Binary Coded Decimal (BCD) format.
//! In BCD, each decimal digit is represented by its 4-bit binary equivalent.
//!
//! # Examples
//!
//! ```
//! use the_algorithms_rust::bit_manipulation::binary_coded_dec... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/mod.rs | src/bit_manipulation/mod.rs | mod binary_coded_decimal;
mod binary_count_trailing_zeros;
mod counting_bits;
mod find_missing_number;
mod find_previous_power_of_two;
mod find_unique_number;
mod hamming_distance;
mod highest_set_bit;
mod is_power_of_two;
mod n_bits_gray_code;
mod reverse_bits;
mod rightmost_set_bit;
mod sum_of_two_integers;
mod swap_... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/sum_of_two_integers.rs | src/bit_manipulation/sum_of_two_integers.rs | //! This module provides a function to add two integers without using the `+` operator.
//! It relies on bitwise operations (XOR and AND) to compute the sum, simulating the addition process.
/// Adds two integers using bitwise operations.
///
/// # Arguments
///
/// * `a` - The first integer to be added.
/// * `b` - T... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/is_power_of_two.rs | src/bit_manipulation/is_power_of_two.rs | //! Power of Two Check
//!
//! This module provides a function to determine if a given positive integer is a power of two
//! using efficient bit manipulation.
//!
//! # Algorithm
//!
//! The algorithm uses the property that powers of two have exactly one bit set in their
//! binary representation. When we subtract 1 f... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/bit_manipulation/hamming_distance.rs | src/bit_manipulation/hamming_distance.rs | //! Hamming Distance
//!
//! This module implements the [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance)
//! algorithm for both integers and strings.
//!
//! The Hamming distance between two values is the number of positions at which
//! the corresponding symbols differ.
/// Counts the number of set ... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/compression/move_to_front.rs | src/compression/move_to_front.rs | // https://en.wikipedia.org/wiki/Move-to-front_transform
fn blank_char_table() -> Vec<char> {
(0..=255).map(|ch| ch as u8 as char).collect()
}
pub fn move_to_front_encode(text: &str) -> Vec<u8> {
let mut char_table = blank_char_table();
let mut result = Vec::new();
for ch in text.chars() {
if... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/compression/huffman_encoding.rs | src/compression/huffman_encoding.rs | //! Huffman Encoding implementation
//!
//! Huffman coding is a lossless data compression algorithm that assigns variable-length codes
//! to characters based on their frequency of occurrence. Characters that occur more frequently
//! are assigned shorter codes, while less frequent characters get longer codes.
//!
//! ... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/compression/run_length_encoding.rs | src/compression/run_length_encoding.rs | // https://en.wikipedia.org/wiki/Run-length_encoding
pub fn run_length_encode(text: &str) -> Vec<(char, i32)> {
let mut count = 1;
let mut encoded: Vec<(char, i32)> = vec![];
for (i, c) in text.chars().enumerate() {
if i + 1 < text.len() && c == text.chars().nth(i + 1).unwrap() {
count... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/compression/lz77.rs | src/compression/lz77.rs | //! LZ77 Compression Algorithm
//!
//! LZ77 is a lossless data compression algorithm published by Abraham Lempel and Jacob Ziv in 1977.
//! Also known as LZ1 or sliding-window compression, it forms the basis for many variations
//! including LZW, LZSS, LZMA and others.
//!
//! # Algorithm Overview
//!
//! It uses a "sl... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/compression/mod.rs | src/compression/mod.rs | mod burrows_wheeler_transform;
mod huffman_encoding;
mod lz77;
mod move_to_front;
mod run_length_encoding;
pub use self::burrows_wheeler_transform::{all_rotations, bwt_transform, reverse_bwt, BwtResult};
pub use self::huffman_encoding::{huffman_decode, huffman_encode};
pub use self::lz77::{LZ77Compressor, Token};
pub ... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/compression/burrows_wheeler_transform.rs | src/compression/burrows_wheeler_transform.rs | //! Burrows-Wheeler Transform
//!
//! The Burrows-Wheeler transform (BWT, also called block-sorting compression)
//! rearranges a character string into runs of similar characters. This is useful
//! for compression, since it tends to be easy to compress a string that has runs
//! of repeated characters by techniques su... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/number_theory/mod.rs | src/number_theory/mod.rs | mod compute_totient;
mod euler_totient;
mod kth_factor;
pub use self::compute_totient::compute_totient;
pub use self::euler_totient::euler_totient;
pub use self::kth_factor::kth_factor;
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/number_theory/euler_totient.rs | src/number_theory/euler_totient.rs | pub fn euler_totient(n: u64) -> u64 {
let mut result = n;
let mut num = n;
let mut p = 2;
// Find all prime factors and apply formula
while p * p <= num {
// Check if p is a divisor of n
if num.is_multiple_of(p) {
// If yes, then it is a prime factor
// Appl... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/number_theory/compute_totient.rs | src/number_theory/compute_totient.rs | // Totient function for
// all numbers smaller than
// or equal to n.
// Computes and prints
// totient of all numbers
// smaller than or equal to n
use std::vec;
pub fn compute_totient(n: i32) -> vec::Vec<i32> {
let mut phi: Vec<i32> = Vec::new();
// initialize phi[i] = i
for i in 0..=n {
phi.p... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/number_theory/kth_factor.rs | src/number_theory/kth_factor.rs | // Kth Factor of N
// The idea is to check for each number in the range [N, 1], and print the Kth number that divides N completely.
pub fn kth_factor(n: i32, k: i32) -> i32 {
let mut factors: Vec<i32> = Vec::new();
let k = (k as usize) - 1;
for i in 1..=n {
if n % i == 0 {
factors.push(... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/big_integer/poly1305.rs | src/big_integer/poly1305.rs | use num_bigint::BigUint;
use num_traits::Num;
use num_traits::Zero;
macro_rules! hex_uint {
($a:literal) => {
BigUint::from_str_radix($a, 16).unwrap()
};
}
/**
* Poly1305 Message Authentication Code:
* This implementation is based on RFC8439.
* Note that the Big Integer library we are using may not... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/big_integer/mod.rs | src/big_integer/mod.rs | #![cfg(feature = "big-math")]
mod fast_factorial;
mod multiply;
mod poly1305;
pub use self::fast_factorial::fast_factorial;
pub use self::multiply::multiply;
pub use self::poly1305::Poly1305;
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/big_integer/fast_factorial.rs | src/big_integer/fast_factorial.rs | // Algorithm created by Peter Borwein in 1985
// https://doi.org/10.1016/0196-6774(85)90006-9
use crate::math::sieve_of_eratosthenes;
use num_bigint::BigUint;
use num_traits::One;
use std::collections::BTreeMap;
/// Calculate the sum of n / p^i with integer division for all values of i
fn index(p: usize, n: usize) ->... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/big_integer/multiply.rs | src/big_integer/multiply.rs | /// Performs long multiplication on string representations of non-negative numbers.
pub fn multiply(num1: &str, num2: &str) -> String {
if !is_valid_nonnegative(num1) || !is_valid_nonnegative(num2) {
panic!("String does not conform to specification")
}
if num1 == "0" || num2 == "0" {
return... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/rail_fence.rs | src/ciphers/rail_fence.rs | // wiki: https://en.wikipedia.org/wiki/Rail_fence_cipher
pub fn rail_fence_encrypt(plain_text: &str, key: usize) -> String {
let mut cipher = vec![Vec::new(); key];
for (c, i) in plain_text.chars().zip(zigzag(key)) {
cipher[i].push(c);
}
return cipher.iter().flatten().collect::<String>();
}
p... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/diffie_hellman.rs | src/ciphers/diffie_hellman.rs | // Based on the TheAlgorithms/Python
// RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for
// Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526
use num_bigint::BigUint;
use num_traits::{Num, Zero};
use std::{
collections::HashMap,
sync::LazyLock,
time::{SystemTime, UNIX_EPOC... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/morse_code.rs | src/ciphers/morse_code.rs | use std::collections::HashMap;
use std::io;
const UNKNOWN_CHARACTER: &str = "........";
const _UNKNOWN_MORSE_CHARACTER: &str = "_";
pub fn encode(message: &str) -> String {
let dictionary = _morse_dictionary();
message
.chars()
.map(|char| char.to_uppercase().to_string())
.map(|letter|... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/transposition.rs | src/ciphers/transposition.rs | //! Transposition Cipher
//!
//! The Transposition Cipher is a method of encryption by which a message is shifted
//! according to a regular system, so that the ciphertext is a rearrangement of the
//! original message. The most commonly referred to Transposition Cipher is the
//! COLUMNAR TRANSPOSITION cipher, which i... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/xor.rs | src/ciphers/xor.rs | pub fn xor_bytes(text: &[u8], key: u8) -> Vec<u8> {
text.iter().map(|c| c ^ key).collect()
}
pub fn xor(text: &str, key: u8) -> Vec<u8> {
xor_bytes(text.as_bytes(), key)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_simple() {
let test_string = "test string";
let cipher... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/hashing_traits.rs | src/ciphers/hashing_traits.rs | pub trait Hasher<const DIGEST_BYTES: usize> {
/// return a new instance with default parameters
fn new_default() -> Self;
/// Add new data
fn update(&mut self, data: &[u8]);
/// Returns the hash of current data. If it is necessary does finalization
/// work on the instance, thus it may no long... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/kernighan.rs | src/ciphers/kernighan.rs | pub fn kernighan(n: u32) -> i32 {
let mut count = 0;
let mut n = n;
while n > 0 {
n = n & (n - 1);
count += 1;
}
count
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn count_set_bits() {
assert_eq!(kernighan(0b0000_0000_0000_0000_0000_0000_0000_1011), 3);
... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/sha3.rs | src/ciphers/sha3.rs | /// Size of the state array in bits
const B: usize = 1600;
const W: usize = B / 25;
const L: usize = W.ilog2() as usize;
const U8BITS: usize = u8::BITS as usize;
// Macro for looping through the whole state array
macro_rules! iterate {
( $x:ident, $y:ident, $z:ident => $b:block ) => {
for $y in 0..5 {
... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/chacha.rs | src/ciphers/chacha.rs | macro_rules! quarter_round {
($a:expr,$b:expr,$c:expr,$d:expr) => {
$a = $a.wrapping_add($b);
$d = ($d ^ $a).rotate_left(16);
$c = $c.wrapping_add($d);
$b = ($b ^ $c).rotate_left(12);
$a = $a.wrapping_add($b);
$d = ($d ^ $a).rotate_left(8);
$c = $c.wrapping_ad... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/rsa_cipher.rs | src/ciphers/rsa_cipher.rs | //! RSA Cipher Implementation
//!
//! This module provides a basic implementation of the RSA (Rivest-Shamir-Adleman) encryption algorithm.
//! RSA is an asymmetric cryptographic algorithm that uses a pair of keys: public and private.
//!
//! # Warning
//!
//! This is an educational implementation and should NOT be used... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/caesar.rs | src/ciphers/caesar.rs | const ERROR_MESSAGE: &str = "Rotation must be in the range [0, 25]";
const ALPHABET_LENGTH: u8 = b'z' - b'a' + 1;
/// Encrypts a given text using the Caesar cipher technique.
///
/// In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code,
/// or Caesar shift, is one of the sim... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/blake2b.rs | src/ciphers/blake2b.rs | // For specification go to https://www.rfc-editor.org/rfc/rfc7693
use std::cmp::{max, min};
use std::convert::{TryFrom, TryInto};
type Word = u64;
const BB: usize = 128;
const U64BYTES: usize = (u64::BITS as usize) / 8;
type Block = [Word; BB / U64BYTES];
const KK_MAX: usize = 64;
const NN_MAX: u8 = 64;
// Array... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/base64.rs | src/ciphers/base64.rs | /*
A Rust implementation of a base64 encoder and decoder.
Written from scratch.
*/
// The charset and padding used for en- and decoding.
const CHARSET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const PADDING: char = '=';
/*
Combines the two provided bytes into an u16... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/salsa.rs | src/ciphers/salsa.rs | macro_rules! quarter_round {
($v1:expr,$v2:expr,$v3:expr,$v4:expr) => {
$v2 ^= ($v1.wrapping_add($v4).rotate_left(7));
$v3 ^= ($v2.wrapping_add($v1).rotate_left(9));
$v4 ^= ($v3.wrapping_add($v2).rotate_left(13));
$v1 ^= ($v4.wrapping_add($v3).rotate_left(18));
};
}
/// This is ... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/another_rot13.rs | src/ciphers/another_rot13.rs | pub fn another_rot13(text: &str) -> String {
let input = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
let output = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";
text.chars()
.map(|c| match input.find(c) {
Some(i) => output.chars().nth(i).unwrap(),
None =>... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/rot13.rs | src/ciphers/rot13.rs | pub fn rot13(text: &str) -> String {
let to_enc = text.to_uppercase();
to_enc
.chars()
.map(|c| match c {
'A'..='M' => ((c as u8) + 13) as char,
'N'..='Z' => ((c as u8) - 13) as char,
_ => c,
})
.collect()
}
#[cfg(test)]
mod test {
use sup... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/sha256.rs | src/ciphers/sha256.rs | /*!
* SHA-2 256 bit implementation
* This implementation is based on RFC6234
* Keep in mind that the amount of data (in bits) processed should always be an
* integer multiple of 8
*/
// The constants are tested to make sure they are correct
pub const H0: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54f... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/polybius.rs | src/ciphers/polybius.rs | /// Encode an ASCII string into its location in a Polybius square.
/// Only alphabetical characters are encoded.
pub fn encode_ascii(string: &str) -> String {
string
.chars()
.map(|c| match c {
'a' | 'A' => "11",
'b' | 'B' => "12",
'c' | 'C' => "13",
'... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/aes.rs | src/ciphers/aes.rs | const AES_WORD_SIZE: usize = 4;
const AES_BLOCK_SIZE: usize = 16;
const AES_NUM_BLOCK_WORDS: usize = AES_BLOCK_SIZE / AES_WORD_SIZE;
type Byte = u8;
type Word = u32;
type AesWord = [Byte; AES_WORD_SIZE];
/// Precalculated values for x to the power of 2 in Rijndaels galois field.
/// Used as 'RCON' during the key exp... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/mod.rs | src/ciphers/mod.rs | mod aes;
mod another_rot13;
mod baconian_cipher;
mod base64;
mod blake2b;
mod caesar;
mod chacha;
mod diffie_hellman;
mod hashing_traits;
mod kernighan;
mod morse_code;
mod polybius;
mod rail_fence;
mod rot13;
mod rsa_cipher;
mod salsa;
mod sha256;
mod sha3;
mod tea;
mod theoretical_rot13;
mod transposition;
mod vernam... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/vernam.rs | src/ciphers/vernam.rs | //! Vernam Cipher
//!
//! The Vernam cipher is a symmetric stream cipher where plaintext is combined
//! with a random or pseudorandom stream of data (the key) of the same length.
//! This implementation uses the alphabet A-Z with modular arithmetic.
//!
//! # Algorithm
//!
//! For encryption: C = (P + K) mod 26
//! Fo... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/vigenere.rs | src/ciphers/vigenere.rs | //! Vigenère Cipher
//!
//! # Algorithm
//!
//! Rotate each ascii character by the offset of the corresponding key character.
//! When we reach the last key character, we start over from the first one.
//! This implementation does not rotate unicode characters.
/// Vigenère cipher to rotate plain_text text by key and ... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/tea.rs | src/ciphers/tea.rs | use std::num::Wrapping as W;
struct TeaContext {
key0: u64,
key1: u64,
}
impl TeaContext {
pub fn new(key: &[u64; 2]) -> TeaContext {
TeaContext {
key0: key[0],
key1: key[1],
}
}
pub fn encrypt_block(&self, block: u64) -> u64 {
let (mut b0, mut b1) ... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/baconian_cipher.rs | src/ciphers/baconian_cipher.rs | // Author : cyrixninja
//Program to encode and decode Baconian or Bacon's Cipher
//Wikipedia reference : https://en.wikipedia.org/wiki/Bacon%27s_cipher
// Bacon's cipher or the Baconian cipher is a method of steganographic message encoding devised by Francis Bacon in 1605.
// A message is concealed in the presentation ... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/ciphers/theoretical_rot13.rs | src/ciphers/theoretical_rot13.rs | // in theory rot-13 only affects the lowercase characters in a cipher
pub fn theoretical_rot13(text: &str) -> String {
let mut pos: u8 = 0;
let mut npos: u8 = 0;
text.to_owned()
.chars()
.map(|mut c| {
if c.is_ascii_lowercase() {
// ((c as u8) + 13) as char
... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/two_sum.rs | src/general/two_sum.rs | use std::collections::HashMap;
/// Given an array of integers nums and an integer target,
/// return indices of the two numbers such that they add up to target.
///
/// # Parameters
///
/// - `nums`: A list of numbers to check.
/// - `target`: The target sum.
///
/// # Returns
///
/// If the target sum is found in the... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/hanoi.rs | src/general/hanoi.rs | pub fn hanoi(n: i32, from: i32, to: i32, via: i32, moves: &mut Vec<(i32, i32)>) {
if n > 0 {
hanoi(n - 1, from, via, to, moves);
moves.push((from, to));
hanoi(n - 1, via, to, from, moves);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hanoi_simple() {
let co... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/kmeans.rs | src/general/kmeans.rs | // Macro to implement kmeans for both f64 and f32 without writing everything
// twice or importing the `num` crate
macro_rules! impl_kmeans {
($kind: ty, $modname: ident) => {
// Since we can't overload methods in rust, we have to use namespacing
pub mod $modname {
/// computes sum of s... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/huffman_encoding.rs | src/general/huffman_encoding.rs | use std::{
cmp::Ordering,
collections::{BTreeMap, BinaryHeap},
};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
pub struct HuffmanValue {
// For the `value` to overflow, the sum of frequencies should be bigger
// than u64. So we should be safe here
/// The encoded value
... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/fisher_yates_shuffle.rs | src/general/fisher_yates_shuffle.rs | use std::time::{SystemTime, UNIX_EPOCH};
use crate::math::PCG32;
const DEFAULT: u64 = 4294967296;
fn gen_range(range: usize, generator: &mut PCG32) -> usize {
generator.get_u64() as usize % range
}
pub fn fisher_yates_shuffle(array: &mut [i32]) {
let seed = match SystemTime::now().duration_since(UNIX_EPOCH)... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/genetic.rs | src/general/genetic.rs | use std::cmp::Ordering;
use std::collections::BTreeSet;
use std::fmt::Debug;
/// The goal is to showcase how Genetic algorithms generically work
/// See: https://en.wikipedia.org/wiki/Genetic_algorithm for concepts
/// This is the definition of a Chromosome for a genetic algorithm
/// We can picture this as "one cont... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/convex_hull.rs | src/general/convex_hull.rs | use std::cmp::Ordering::Equal;
fn sort_by_min_angle(pts: &[(f64, f64)], min: &(f64, f64)) -> Vec<(f64, f64)> {
let mut points: Vec<(f64, f64, (f64, f64))> = pts
.iter()
.map(|x| {
(
(x.1 - min.1).atan2(x.0 - min.0),
// angle
(x.1 - min.1).... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/mod.rs | src/general/mod.rs | mod convex_hull;
mod fisher_yates_shuffle;
mod genetic;
mod hanoi;
mod huffman_encoding;
mod kadane_algorithm;
mod kmeans;
mod mex;
mod permutations;
mod two_sum;
pub use self::convex_hull::convex_hull_graham;
pub use self::fisher_yates_shuffle::fisher_yates_shuffle;
pub use self::genetic::GeneticAlgorithm;
pub use se... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/kadane_algorithm.rs | src/general/kadane_algorithm.rs | /**
* @file
* @brief Find the maximum subarray sum using Kadane's algorithm.(https://en.wikipedia.org/wiki/Maximum_subarray_problem)
*
* @details
* This program provides a function to find the maximum subarray sum in an array of integers
* using Kadane's algorithm.
*
* @param arr A slice of integers representin... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/mex.rs | src/general/mex.rs | use std::collections::BTreeSet;
// Find minimum excluded number from a set of given numbers using a set
/// Finds the MEX of the values provided in `arr`
/// Uses [`BTreeSet`](std::collections::BTreeSet)
/// O(nlog(n)) implementation
pub fn mex_using_set(arr: &[i64]) -> i64 {
let mut s: BTreeSet<i64> = BTreeSet::n... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/permutations/steinhaus_johnson_trotter.rs | src/general/permutations/steinhaus_johnson_trotter.rs | /// <https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm>
pub fn steinhaus_johnson_trotter_permute<T: Clone>(array: &[T]) -> Vec<Vec<T>> {
let len = array.len();
let mut array = array.to_owned();
let mut inversion_vector = vec![0; len];
let mut i = 1;
let mut res = Vec:... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/permutations/naive.rs | src/general/permutations/naive.rs | use std::collections::HashSet;
use std::fmt::Debug;
use std::hash::Hash;
/// Here's a basic (naive) implementation for generating permutations
pub fn permute<T: Clone + Debug>(arr: &[T]) -> Vec<Vec<T>> {
if arr.is_empty() {
return vec![vec![]];
}
let n = arr.len();
let count = (1..=n).product()... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/permutations/mod.rs | src/general/permutations/mod.rs | mod heap;
mod naive;
mod steinhaus_johnson_trotter;
pub use self::heap::heap_permute;
pub use self::naive::{permute, permute_unique};
pub use self::steinhaus_johnson_trotter::steinhaus_johnson_trotter_permute;
#[cfg(test)]
mod tests {
use quickcheck::{Arbitrary, Gen};
use std::collections::HashMap;
pub f... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/general/permutations/heap.rs | src/general/permutations/heap.rs | use std::fmt::Debug;
/// Computes all permutations of an array using Heap's algorithm
/// Read `recurse_naive` first, since we're building on top of the same intuition
pub fn heap_permute<T: Clone + Debug>(arr: &[T]) -> Vec<Vec<T>> {
if arr.is_empty() {
return vec![vec![]];
}
let n = arr.len();
... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/navigation/rhumbline.rs | src/navigation/rhumbline.rs | use std::f64::consts::PI;
const EARTH_RADIUS: f64 = 6371000.0;
pub fn rhumb_dist(lat1: f64, long1: f64, lat2: f64, long2: f64) -> f64 {
let phi1 = lat1 * PI / 180.00;
let phi2 = lat2 * PI / 180.00;
let del_phi = phi2 - phi1;
let mut del_lambda = (long2 - long1) * PI / 180.00;
if del_lambda > PI {... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/navigation/bearing.rs | src/navigation/bearing.rs | use std::f64::consts::PI;
pub fn bearing(lat1: f64, lng1: f64, lat2: f64, lng2: f64) -> f64 {
let lat1 = lat1 * PI / 180.0;
let lng1 = lng1 * PI / 180.0;
let lat2 = lat2 * PI / 180.0;
let lng2 = lng2 * PI / 180.0;
let delta_longitude = lng2 - lng1;
let y = delta_longitude.sin() * lat2.cos();... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/navigation/mod.rs | src/navigation/mod.rs | mod bearing;
mod haversine;
mod rhumbline;
pub use self::bearing::bearing;
pub use self::haversine::haversine;
pub use self::rhumbline::rhumb_bearing;
pub use self::rhumbline::rhumb_destination;
pub use self::rhumbline::rhumb_dist;
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/navigation/haversine.rs | src/navigation/haversine.rs | use std::f64::consts::PI;
const EARTH_RADIUS: f64 = 6371000.00;
pub fn haversine(lat1: f64, lng1: f64, lat2: f64, lng2: f64) -> f64 {
let delta_dist_lat = (lat2 - lat1) * PI / 180.0;
let delta_dist_lng = (lng2 - lng1) * PI / 180.0;
let cos1 = lat1 * PI / 180.0;
let cos2 = lat2 * PI / 180.0;
let ... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/signal_analysis/mod.rs | src/signal_analysis/mod.rs | mod yin;
pub use self::yin::{Yin, YinResult};
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/signal_analysis/yin.rs | src/signal_analysis/yin.rs | use std::f64;
#[derive(Clone, Debug)]
pub struct YinResult {
sample_rate: f64,
best_lag: usize,
cmndf: Vec<f64>,
}
impl YinResult {
pub fn get_frequency(&self) -> f64 {
self.sample_rate / self.best_lag as f64
}
pub fn get_frequency_with_interpolation(&self) -> f64 {
let best_l... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/greedy/mod.rs | src/greedy/mod.rs | mod stable_matching;
pub use self::stable_matching::stable_matching;
| rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/greedy/stable_matching.rs | src/greedy/stable_matching.rs | use std::collections::{HashMap, VecDeque};
fn initialize_men(
men_preferences: &HashMap<String, Vec<String>>,
) -> (VecDeque<String>, HashMap<String, usize>) {
let mut free_men = VecDeque::new();
let mut next_proposal = HashMap::new();
for man in men_preferences.keys() {
free_men.push_back(man... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/compound_interest.rs | src/financial/compound_interest.rs | // compound interest is given by A = P(1+r/n)^nt
// where: A = Final Amount, P = Principal Amount, r = rate of interest,
// n = number of times interest is compounded per year and t = time (in years)
pub fn compound_interest(principal: f64, rate: f64, comp_per_year: u32, years: f64) -> f64 {
principal * (1.00 + ra... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/present_value.rs | src/financial/present_value.rs | /// In economics and finance, present value (PV), also known as present discounted value,
/// is the value of an expected income stream determined as of the date of valuation.
///
/// -> Wikipedia reference: https://en.wikipedia.org/wiki/Present_value
#[derive(PartialEq, Eq, Debug)]
pub enum PresentValueError {
Ne... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/treynor_ratio.rs | src/financial/treynor_ratio.rs | /// Calculates the Treynor Ratio for a portfolio.
///
/// # Inputs
/// - `portfolio_return`: Portfolio return
/// - `risk_free_rate`: Risk-free rate
/// - `beta`: Portfolio beta
/// where Beta is a financial metric that measures the systematic risk of a security or portfolio compared to the overall market.
///
/// # Ou... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/payback.rs | src/financial/payback.rs | /// Returns the payback period in years
/// If investment is not paid back, returns None.
pub fn payback(cash_flow: &[f64]) -> Option<usize> {
let mut total = 0.00;
for (year, &cf) in cash_flow.iter().enumerate() {
total += cf;
if total >= 0.00 {
return Some(year);
}
}
... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/mod.rs | src/financial/mod.rs | mod compound_interest;
mod finance_ratios;
mod npv;
mod npv_sensitivity;
mod payback;
mod present_value;
mod treynor_ratio;
pub use compound_interest::compound_interest;
pub use npv::npv;
pub use npv_sensitivity::npv_sensitivity;
pub use payback::payback;
pub use present_value::present_value;
pub use treynor_ratio::tre... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/npv_sensitivity.rs | src/financial/npv_sensitivity.rs | /// Computes the Net Present Value (NPV) of a cash flow series
/// at multiple discount rates to show sensitivity.
///
/// # Inputs:
/// - `cash_flows`: A slice of cash flows, where each entry is a period value
/// e.g., year 0 is initial investment, year 1+ are returns or costs
/// - `discount_rates`: A slice of dis... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/npv.rs | src/financial/npv.rs | /// Calculates Net Present Value given a vector of cash flows and a discount rate.
/// cash_flows: Vector of f64 representing cash flows for each period.
/// rate: Discount rate as an f64 (e.g., 0.05 for 5%)
pub fn npv(cash_flows: &[f64], rate: f64) -> f64 {
cash_flows
.iter()
.enumerate()
... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/financial/finance_ratios.rs | src/financial/finance_ratios.rs | // Calculating simple ratios like Return on Investment (ROI), Debt to Equity, Gross Profit Margin
// and Earnings per Sale (EPS)
pub fn return_on_investment(gain: f64, cost: f64) -> f64 {
(gain - cost) / cost
}
pub fn debt_to_equity(debt: f64, equity: f64) -> f64 {
debt / equity
}
pub fn gross_profit_margin(r... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/quick_sort_3_ways.rs | src/sorting/quick_sort_3_ways.rs | use std::cmp::{Ord, Ordering};
use rand::Rng;
fn _quick_sort_3_ways<T: Ord>(arr: &mut [T], lo: usize, hi: usize) {
if lo >= hi {
return;
}
let mut rng = rand::rng();
arr.swap(lo, rng.random_range(lo..=hi));
let mut lt = lo; // arr[lo+1, lt] < v
let mut gt = hi + 1; // arr[gt, r] > v
... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/heap_sort.rs | src/sorting/heap_sort.rs | //! This module provides functions for heap sort algorithm.
use std::cmp::Ordering;
/// Builds a heap from the provided array.
///
/// This function builds either a max heap or a min heap based on the `is_max_heap` parameter.
///
/// # Arguments
///
/// * `arr` - A mutable reference to the array to be sorted.
/// * `... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/cocktail_shaker_sort.rs | src/sorting/cocktail_shaker_sort.rs | pub fn cocktail_shaker_sort<T: Ord>(arr: &mut [T]) {
let len = arr.len();
if len == 0 {
return;
}
loop {
let mut swapped = false;
for i in 0..(len - 1).clamp(0, len) {
if arr[i] > arr[i + 1] {
arr.swap(i, i + 1);
swapped = true;
... | rust | MIT | 38024b01c29eb05f733d480f88f19f0c06922a85 | 2026-01-04T15:37:39.002409Z | false |
TheAlgorithms/Rust | https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/sorting/wiggle_sort.rs | src/sorting/wiggle_sort.rs | //Wiggle Sort.
//Given an unsorted array nums, reorder it such
//that nums[0] < nums[1] > nums[2] < nums[3]....
//For example:
//if input numbers = [3, 5, 2, 1, 6, 4]
//one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
pub fn wiggle_sort(nums: &mut Vec<i32>) -> &mut Vec<i32> {
//Rust implementation of wiggl... | 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.