id
stringlengths
18
18
chunk_id
stringlengths
16
16
repo
stringclasses
6 values
repo_url
stringclasses
6 values
commit
stringclasses
6 values
license
stringclasses
4 values
path
stringlengths
10
68
kind
stringclasses
1 value
name
stringlengths
5
44
context
stringlengths
10
68
start_line
int32
1
1
end_line
int32
3
1.42k
num_lines
int32
3
1.42k
question
stringlengths
133
1.46k
answer
stringlengths
44
54.5k
model
stringclasses
1 value
fe41c1b7152c17a4-0
fe41c1b7152c17a4
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/backtracking/graph_coloring.rs
file
graph_coloring.rs
src/backtracking/graph_coloring.rs
1
370
370
I need a Rust module that generates all valid colorings of a graph represented by an adjacency matrix. The implementation should use backtracking to assign colors from 0 to num_colors-1 to each vertex, ensuring no two adjacent vertices share the same color (checking both adjacency_matrix[i][j] and adjacency_matrix[j][i...
//! This module provides functionality for generating all possible colorings of a undirected (or directed) graph //! given a certain number of colors. It includes the GraphColoring struct and methods //! for validating color assignments and finding all valid colorings. /// Represents potential errors when coloring on ...
nvidia/nemotron-3.5-lightning-30b-a3b
e3d9fc4214373c94-0
e3d9fc4214373c94
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/backtracking/hamiltonian_cycle.rs
file
hamiltonian_cycle.rs
src/backtracking/hamiltonian_cycle.rs
1
310
310
I need a Rust module for finding a Hamiltonian cycle in a directed or undirected graph represented by an adjacency matrix. The module should expose an error enum with variants for empty/malformed matrices and out-of-bounds start vertices, a `Graph` struct wrapping the adjacency matrix, and a public function that takes ...
//! This module provides functionality to find a Hamiltonian cycle in a directed or undirected graph. //! Source: [Wikipedia](https://en.wikipedia.org/wiki/Hamiltonian_path_problem) /// Represents potential errors when finding hamiltonian cycle on an adjacency matrix. #[derive(Debug, PartialEq, Eq)] pub enum FindHamil...
nvidia/nemotron-3.5-lightning-30b-a3b
0ef042b601d34e7f-0
0ef042b601d34e7f
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/backtracking/permutations.rs
file
permutations.rs
src/backtracking/permutations.rs
1
141
141
I need a Rust function `permute` that generates all distinct permutations of a vector of integers. The function should sort the input vector first to handle duplicates effectively, then use a recursive backtracking algorithm that tracks which elements have been used and skips over duplicate values when the previous ide...
//! This module provides a function to generate all possible distinct permutations //! of a given collection of integers using a backtracking algorithm. /// Generates all possible distinct permutations of a given vector of integers. /// /// # Arguments /// /// * `nums` - A vector of integers. The input vector is sorte...
nvidia/nemotron-3.5-lightning-30b-a3b
17bd026994000658-0
17bd026994000658
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/backtracking/mod.rs
file
mod.rs
src/backtracking/mod.rs
1
21
21
I need a Rust module that declares several backtracking algorithm submodules and re-exports their public functions. The module should define submodules named all_combination_of_size_k, graph_coloring, hamiltonian_cycle, knight_tour, n_queens, parentheses_generator, permutations, rat_in_maze, subset_sum, and sudoku. It ...
mod all_combination_of_size_k; mod graph_coloring; mod hamiltonian_cycle; mod knight_tour; mod n_queens; mod parentheses_generator; mod permutations; mod rat_in_maze; mod subset_sum; mod sudoku; pub use all_combination_of_size_k::generate_all_combinations; pub use graph_coloring::generate_colorings; pub use hamiltonia...
nvidia/nemotron-3.5-lightning-30b-a3b
025753790b6f4339-0
025753790b6f4339
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/backtracking/n_queens.rs
file
n_queens.rs
src/backtracking/n_queens.rs
1
221
221
I need a Rust module that solves the N-Queens problem using backtracking. The module should define a public function `n_queens_solver(n: usize) -> Vec<Vec<String>>` that returns all distinct solutions for an `n×n` board, where each solution is a vector of strings representing rows with `'Q'` for queens and `'.'` for em...
//! This module provides functionality to solve the N-Queens problem. //! //! The N-Queens problem is a classic chessboard puzzle where the goal is to //! place N queens on an NxN chessboard so that no two queens threaten each //! other. Queens can attack each other if they share the same row, column, or //! diagonal. ...
nvidia/nemotron-3.5-lightning-30b-a3b
095318a5152a36f4-0
095318a5152a36f4
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/backtracking/all_combination_of_size_k.rs
file
all_combination_of_size_k.rs
src/backtracking/all_combination_of_size_k.rs
1
123
123
I need a Rust module that generates all possible combinations of `k` numbers chosen from the range `0` to `n-1` using a backtracking algorithm. The module should define a public error enum `CombinationError` with two variants: `KGreaterThanN` and `InvalidZeroRange`. Provide a public function `generate_all_combinations(...
//! This module provides a function to generate all possible combinations //! of `k` numbers out of `0...n-1` using a backtracking algorithm. /// Custom error type for combination generation. #[derive(Debug, PartialEq)] pub enum CombinationError { KGreaterThanN, InvalidZeroRange, } /// Generates all possible ...
nvidia/nemotron-3.5-lightning-30b-a3b
9062a572e1244df7-0
9062a572e1244df7
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/backtracking/sudoku.rs
file
sudoku.rs
src/backtracking/sudoku.rs
1
164
164
I need a Rust module that implements a Sudoku solver using the backtracking algorithm. The module should expose a public function `sudoku_solver` that accepts a `&[[u8; 9]; 9]` and returns `Option<[[u8; 9]; 9]>`, returning the solved board or `None` if unsolvable. Additionally, define a `SudokuSolver` struct with a `bo...
//! A Rust implementation of Sudoku solver using Backtracking. //! //! This module provides functionality to solve Sudoku puzzles using the backtracking algorithm. //! //! GeeksForGeeks: [Sudoku Backtracking](https://www.geeksforgeeks.org/sudoku-backtracking-7/) /// Solves a Sudoku puzzle. /// /// Given a partially fi...
nvidia/nemotron-3.5-lightning-30b-a3b
99fbf83e1ab99c58-0
99fbf83e1ab99c58
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/backtracking/subset_sum.rs
file
subset_sum.rs
src/backtracking/subset_sum.rs
1
55
55
I need a Rust function `has_subset_with_sum` that determines if a subset of a given slice of `isize` integers adds up to a target `isize`. The function should use recursive backtracking: at each step, it either skips the current element or includes it by subtracting it from the target. A helper function `backtrack` sho...
//! This module provides functionality to check if there exists a subset of a given set of integers //! that sums to a target value. The implementation uses a recursive backtracking approach. /// Checks if there exists a subset of the given set that sums to the target value. pub fn has_subset_with_sum(set: &[isize], t...
nvidia/nemotron-3.5-lightning-30b-a3b
32de02c803b75dbf-0
32de02c803b75dbf
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/big_integer/fast_factorial.rs
file
fast_factorial.rs
src/big_integer/fast_factorial.rs
1
87
87
I need a Rust function `fast_factorial` that computes the factorial of a non-negative integer `n` using Peter Borwein's 1985 algorithm. The input is a `usize` and the output is a `num_bigint::BigUint`. The algorithm should first generate all primes up to `n` using a function `sieve_of_eratosthenes`. Then, for each prim...
// 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) ->...
nvidia/nemotron-3.5-lightning-30b-a3b
060d812d7a308209-0
060d812d7a308209
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/backtracking/knight_tour.rs
file
knight_tour.rs
src/backtracking/knight_tour.rs
1
195
195
Write a Rust module for the Knight's Tour problem using backtracking. The module must export a function `find_knight_tour(size_x: usize, size_y: usize, start_x: usize, start_y: usize) -> Option<Vec<Vec<usize>>>` that returns a board matrix of move orders, or `None` if no tour exists. Include a `KnightTour` struct with ...
//! This module contains the implementation of the Knight's Tour problem. //! //! The Knight's Tour is a classic chess problem where the objective is to move a knight to every square on a chessboard exactly once. /// Finds the Knight's Tour starting from the specified position. /// /// # Arguments /// /// * `size_x` -...
nvidia/nemotron-3.5-lightning-30b-a3b
4710d1a963b9ea27-0
4710d1a963b9ea27
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/bit_manipulation/counting_bits.rs
file
counting_bits.rs
src/bit_manipulation/counting_bits.rs
1
54
54
I need a Rust function that counts the number of set bits (1s) in the binary representation of an unsigned integer using Brian Kernighan's algorithm. The function should accept a usize and return a usize. It should iteratively clear the least significant set bit via n &= n - 1 until n is zero, running in O(k) time wher...
//! 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...
nvidia/nemotron-3.5-lightning-30b-a3b
f37c8db473350605-0
f37c8db473350605
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/bit_manipulation/highest_set_bit.rs
file
highest_set_bit.rs
src/bit_manipulation/highest_set_bit.rs
1
52
52
I need a Rust function named `find_highest_set_bit` that accepts a `usize` and returns `Option<usize>`. The function should find the position of the most significant bit set to 1 using 0-based indexing. If the input is 0, it should return `None`. The implementation should use a simple loop that right-shifts the number ...
//! 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...
nvidia/nemotron-3.5-lightning-30b-a3b
824ca5bbfbf41e32-0
824ca5bbfbf41e32
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/backtracking/parentheses_generator.rs
file
parentheses_generator.rs
src/backtracking/parentheses_generator.rs
1
76
76
I need a Rust implementation that generates every valid combination of well-formed parentheses for a given non-negative integer n using a backtracking approach. The solution should expose a function generate_parentheses(n: usize) -> Vec<String> that returns all possible strings of n pairs of parentheses. I'd also like ...
/// Generates all combinations of well-formed parentheses given a non-negative integer `n`. /// /// This function uses backtracking to generate all possible combinations of well-formed /// parentheses. The resulting combinations are returned as a vector of strings. /// /// # Arguments /// /// * `n` - A non-negative int...
nvidia/nemotron-3.5-lightning-30b-a3b
f866ecdd366ffd1d-0
f866ecdd366ffd1d
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/big_integer/poly1305.rs
file
poly1305.rs
src/big_integer/poly1305.rs
1
98
98
Write a Rust function/module for Poly1305 MAC using `num_bigint` and `num_traits`, following RFC8439, with key setup, message processing, and tag output.
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...
nvidia/nemotron-3.5-lightning-30b-a3b
6ef07d6e3e430990-0
6ef07d6e3e430990
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/bit_manipulation/n_bits_gray_code.rs
file
n_bits_gray_code.rs
src/bit_manipulation/n_bits_gray_code.rs
1
75
75
I need a Rust function named `generate_gray_code` that takes a `usize` for the number of bits and returns `Result<Vec<String>, GrayCodeError>`. The function should generate an n-bit Gray code sequence using the direct binary formula, return an error if the bit count is zero, and produce a `Vec<String>` where each strin...
/// 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...
nvidia/nemotron-3.5-lightning-30b-a3b
6d634f297152a833-0
6d634f297152a833
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/bit_manipulation/sum_of_two_integers.rs
file
sum_of_two_integers.rs
src/bit_manipulation/sum_of_two_integers.rs
1
55
55
I need a Rust function named `add_two_integers` that adds two `isize` integers using only bitwise XOR and AND operations, without using the `+` operator. The function should simulate ripple-carry addition: compute the sum portion with XOR and the carry with AND left-shifted, then repeat with the carry until it becomes ...
//! 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...
nvidia/nemotron-3.5-lightning-30b-a3b
d6bf5843d57211bb-0
d6bf5843d57211bb
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/ciphers/rail_fence.rs
file
rail_fence.rs
src/ciphers/rail_fence.rs
1
41
41
I need a Rust implementation of the rail fence cipher. Please write `rail_fence_encrypt(plain_text: &str, key: usize) -> String` and `rail_fence_decrypt(cipher: &str, key: usize) -> String`, plus a `zigzag` helper iterator. The cipher should write characters in a zigzag pattern across `key` rails and read them off sequ...
// 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...
nvidia/nemotron-3.5-lightning-30b-a3b
f045284c2dc0dabf-0
f045284c2dc0dabf
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/big_integer/mod.rs
file
mod.rs
src/big_integer/mod.rs
1
9
9
Write a Rust module file for a big_integer module that conditionally compiles only when the `big-math` feature is enabled, declares three submodules (`fast_factorial`, `multiply`, `poly1305`), and re-exports their public `fast_factorial` function, `multiply` function, and `Poly1305` type.
#![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;
nvidia/nemotron-3.5-lightning-30b-a3b
3dac988b6b26a7fc-0
3dac988b6b26a7fc
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/ciphers/kernighan.rs
file
kernighan.rs
src/ciphers/kernighan.rs
1
23
23
Write a Rust function named `kernighan` that counts the number of set bits in a `u32` integer using Brian Kernighan's algorithm. The function should accept a `u32` as input and return an `i32` representing the bit count, clearing the lowest set bit iteratively with `n = n & (n - 1)` until the input reaches zero. Ensure...
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); ...
nvidia/nemotron-3.5-lightning-30b-a3b
d7f15ac81adb3c63-0
d7f15ac81adb3c63
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/compression/mod.rs
file
mod.rs
src/compression/mod.rs
1
13
13
I need a Rust module file for a compression crate that aggregates several standard algorithms into a single public API. The file should declare six submodules: `burrows_wheeler_transform`, `huffman_encoding`, `lz77`, `move_to_front`, `peak_signal_to_noise_ratio`, and `run_length_encoding`. After the module declarations...
mod burrows_wheeler_transform; mod huffman_encoding; mod lz77; mod move_to_front; mod peak_signal_to_noise_ratio; 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::lz7...
nvidia/nemotron-3.5-lightning-30b-a3b
1c93a2599a24d4c0-0
1c93a2599a24d4c0
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/conversions/decimal_to_binary.rs
file
decimal_to_binary.rs
src/conversions/decimal_to_binary.rs
1
26
26
Write a Rust function that converts a u64 decimal number into its binary string representation. The function should use repeated division by 2, collecting the remainder as bits, and then reverse the collected bits to produce the final binary string. The function takes a single u64 argument and returns a String. Include...
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(); ...
nvidia/nemotron-3.5-lightning-30b-a3b
3dbb381383b8293b-0
3dbb381383b8293b
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/conversions/decimal_to_octal.rs
file
decimal_to_octal.rs
src/conversions/decimal_to_octal.rs
1
37
37
I need a Rust function that converts a decimal unsigned 64-bit integer to its octal string representation using repeated division by 8. The function should explicitly handle zero, collect remainders as digits, reverse them, and return the result as a String. Include unit tests asserting the outputs for decimal 0, 8, 15...
// Author: NithinU2802 // Decimal to Octal Converter: Converts Decimal to Octal // Wikipedia References: // 1. https://en.wikipedia.org/wiki/Decimal // 2. https://en.wikipedia.org/wiki/Octal pub fn decimal_to_octal(decimal_num: u64) -> String { if decimal_num == 0 { return "0".to_string(); } let m...
nvidia/nemotron-3.5-lightning-30b-a3b
eb906653e579b1e7-0
eb906653e579b1e7
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/compression/move_to_front.rs
file
move_to_front.rs
src/compression/move_to_front.rs
1
60
60
I need a Rust module that implements the Move-to-Front transform for data compression. It must include an `encode` function taking `&str` and returning `Vec<u8>`, where each byte is the index of the character in a 256-element table that moves the character to the front after recording. Also implement a `decode` functio...
// 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...
nvidia/nemotron-3.5-lightning-30b-a3b
c846c0321779cffe-0
c846c0321779cffe
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/conversions/mod.rs
file
mod.rs
src/conversions/mod.rs
1
55
55
I need a Rust module file that organizes and re-exports a comprehensive set of conversion functions and types for a algorithms library. The module should support converting between numeric bases (binary, decimal, hexadecimal, octal) in both directions, converting energy values with their unit types, handling IPv4 addre...
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 energy; mod hexadecimal_to_binary; mod hexadecimal_to_decimal; mod hexadecimal_to_octal; mod ipv4_conversion; mod length_conversion; mod octal_to_binary; mod octal_to_decim...
nvidia/nemotron-3.5-lightning-30b-a3b
98444a461d6fc629-0
98444a461d6fc629
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/data_structures/b_tree.rs
file
b_tree.rs
src/data_structures/b_tree.rs
1
209
209
I need a complete Rust module implementing a B-tree data structure. The implementation should include a `Node` struct, a `BTreeProps` struct to store tree properties like degree, max keys, and mid key index, and a `BTree` generic struct parameterized over type `T`. The type `T` must implement `Ord`, `Copy`, `Debug`, an...
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-...
nvidia/nemotron-3.5-lightning-30b-a3b
b367182bd288997f-0
b367182bd288997f
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/bit_manipulation/mod.rs
file
mod.rs
src/bit_manipulation/mod.rs
1
35
35
I need a Rust module file that sets up a bit manipulation crate with several submodules, each exporting specific functions at the crate root. The structure should include submodules for binary coded decimal, bit counting, bit shifts, finding missing numbers, power-of-two operations, Hamming distance, highest set bit, G...
mod binary_coded_decimal; mod binary_count_trailing_zeros; mod binary_shifts; 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_...
nvidia/nemotron-3.5-lightning-30b-a3b
939fa086d710739b-0
939fa086d710739b
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/conversions/rgb_cmyk_conversion.rs
file
rgb_cmyk_conversion.rs
src/conversions/rgb_cmyk_conversion.rs
1
60
60
Write a Rust function `rgb_to_cmyk` that takes a tuple `(u8, u8, u8)` representing red, green, and blue components and returns a tuple `(u8, u8, u8, u8)` of cyan, magenta, yellow, and key (black) values. The conversion should scale the inputs to [0, 1], compute K as `1 - max(r, g, b)`, and derive C, M, Y using `100 * (...
/// 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,...
nvidia/nemotron-3.5-lightning-30b-a3b
8f9315ace65fea20-0
8f9315ace65fea20
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/conversions/rectangular_to_polar.rs
file
rectangular_to_polar.rs
src/conversions/rectangular_to_polar.rs
1
47
47
Write a Rust function `rectangular_to_polar` that converts rectangular (Cartesian) coordinates given as `f64` real and imaginary parts into polar coordinates. It should return a tuple of two `f64` values: the magnitude and the angle in degrees. The angle must be computed using `atan2` and converted to degrees. Both val...
//! Conversions between rectangular (Cartesian) and polar coordinate systems. //! //! This module provides utilities for converting rectangular coordinates //! into polar coordinates with angles expressed in degrees. //! //! More information: <https://en.wikipedia.org/wiki/Polar_coordinate_system> /// Convert rectangu...
nvidia/nemotron-3.5-lightning-30b-a3b
515d3db37c0f5113-0
515d3db37c0f5113
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/ciphers/mod.rs
file
mod.rs
src/ciphers/mod.rs
1
57
57
I need a Rust source file that serves as a ciphers module. It should declare multiple submodules for different cipher algorithms, then publicly re-export specific functions and types from each submodule using `pub use self::` statements. The re-exports must include exactly: AES encryption and decryption functions along...
mod aes; mod affine_cipher; mod another_rot13; mod baconian_cipher; mod base16; mod base32; mod base64; mod base85; mod caesar; mod chacha; mod diffie_hellman; mod gronsfeld; mod hill_cipher; mod kernighan; mod morse_code; mod polybius; mod rail_fence; mod rot13; mod rsa_cipher; mod salsa; mod tea; mod theoretical_rot1...
nvidia/nemotron-3.5-lightning-30b-a3b
4eb7e2f37d6e2575-0
4eb7e2f37d6e2575
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/ciphers/salsa.rs
file
salsa.rs
src/ciphers/salsa.rs
1
128
128
I want a Rust function `salsa20` that implements the core Salsa20 cipher transformation. It should take `input: &[u32; 16]` and `output: &mut [u32; 16]`, where the 16 words encode the constant `expand 32-byte k` in the first four positions, a 256-bit key in the next eight, and 128 bits each for nonce and counter in the...
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 ...
nvidia/nemotron-3.5-lightning-30b-a3b
480a13a3b83ab358-0
480a13a3b83ab358
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/data_structures/queue.rs
file
queue.rs
src/data_structures/queue.rs
1
91
91
I need a Rust module that implements a generic Queue data structure using std::collections::LinkedList, following FIFO semantics. The queue should support: creating a new empty queue via Queue::new() or Default; enqueuing elements to the back with enqueue(&mut self, value: T); dequeuing the front element and returning ...
//! 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(De...
nvidia/nemotron-3.5-lightning-30b-a3b
b2796ad3d11c6dac-0
b2796ad3d11c6dac
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/data_structures/mod.rs
file
mod.rs
src/data_structures/mod.rs
1
47
47
I'm building a Rust data structures and algorithms library and need a module root file that declares and re-exports several core DS and algorithm modules. The file should define submodules for an AVL tree, a B-tree, a binary search tree, a Fenwick tree, Floyd's cycle detection, directed and undirected graphs, a hash ta...
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_sing...
nvidia/nemotron-3.5-lightning-30b-a3b
7aa8d27f448796f8-0
7aa8d27f448796f8
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/egg_dropping.rs
file
egg_dropping.rs
src/dynamic_programming/egg_dropping.rs
1
84
84
I need a Rust function `egg_drop` that takes `eggs: usize` and `floors: usize` and returns `Option<usize>`, solving the egg dropping puzzle by finding the minimum number of droppings needed to determine the highest floor from which an egg can be dropped without breaking. If `eggs` is 0, return `None`. For 1 egg or when...
//! 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 eg...
nvidia/nemotron-3.5-lightning-30b-a3b
f2dc3995b00c58db-0
f2dc3995b00c58db
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/coin_change.rs
file
coin_change.rs
src/dynamic_programming/coin_change.rs
1
94
94
Write a Rust function `coin_change` that takes `coins: &[usize]` and `amount: usize` and returns `Option<usize>`, implementing the coin change problem via dynamic programming. The function should compute the minimum number of coins needed to make the given amount using the provided denominations, returning `None` if im...
//! 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 solution...
nvidia/nemotron-3.5-lightning-30b-a3b
cd27d531d43ac481-0
cd27d531d43ac481
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/data_structures/probabilistic/bloom_filter.rs
file
bloom_filter.rs
src/data_structures/probabilistic/bloom_filter.rs
1
271
271
I need a complete Rust source file implementing a Bloom Filter probabilistic data structure as a module. The code should define a `BloomFilter` trait parameterized over `Item: Hash` with `insert` and `contains` methods, and provide three concrete types: `BasicBloomFilter<const CAPACITY: usize>` using a fixed-size boole...
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...
nvidia/nemotron-3.5-lightning-30b-a3b
506a536c80be129d-0
506a536c80be129d
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/is_subsequence.rs
file
is_subsequence.rs
src/dynamic_programming/is_subsequence.rs
1
71
71
Write a Rust function `is_subsequence(sub: &str, main: &str) -> bool` that determines whether the string `sub` is a subsequence of `main`. The function should use a peekable iterator over the characters of `sub` and iterate through the characters of `main`; when a character in `main` matches the current character of `s...
//! 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...
nvidia/nemotron-3.5-lightning-30b-a3b
f03a16840cfac9a0-0
f03a16840cfac9a0
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/longest_common_substring.rs
file
longest_common_substring.rs
src/dynamic_programming/longest_common_substring.rs
1
70
70
I need a Rust function named `longest_common_substring` that finds the length of the longest common substring between two strings using dynamic programming. It should accept two `&str` parameters and return `usize`. The implementation must use a 2D DP table where each cell `dp[i][j]` represents the length of the longes...
//! 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 represe...
nvidia/nemotron-3.5-lightning-30b-a3b
8a86f27c7dfb2aeb-0
8a86f27c7dfb2aeb
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/longest_common_subsequence.rs
file
longest_common_subsequence.rs
src/dynamic_programming/longest_common_subsequence.rs
1
116
116
I want a Rust implementation of the longest common subsequence algorithm. Specifically, I need a function named `longest_common_subsequence` that takes two `&str` arguments and returns a `String`. It should handle Unicode correctly by processing characters via `.chars()`, build a dynamic programming table of lengths, a...
//! 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 origina...
nvidia/nemotron-3.5-lightning-30b-a3b
0420043b379c9057-0
0420043b379c9057
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/maximal_square.rs
file
maximal_square.rs
src/dynamic_programming/maximal_square.rs
1
66
66
I need a Rust function maximal_square that takes &mut [Vec<i32>] representing a binary matrix and returns the area of the largest square of 1's. The solution should use dynamic programming with O(m*n) time and O(1) extra space by updating the matrix in place. For each cell equal to 1, if it is in the first row or colum...
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 /// /// # Co...
nvidia/nemotron-3.5-lightning-30b-a3b
fe1eb58045578c4a-0
fe1eb58045578c4a
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/longest_continuous_increasing_subsequence.rs
file
longest_continuous_increasing_subsequence.rs
src/dynamic_programming/longest_continuous_increasing_subsequence.rs
1
93
93
I need a Rust function `longest_continuous_increasing_subsequence` that takes a slice `&[T]` where `T: Ord` and returns the longest contiguous sub-slice where each element is less than or equal to the next element (a non-decreasing run). If there are multiple subsequences of the same length, return the first one found....
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 re...
nvidia/nemotron-3.5-lightning-30b-a3b
acc4d5d97b173548-0
acc4d5d97b173548
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/data_structures/fenwick_tree.rs
file
fenwick_tree.rs
src/data_structures/fenwick_tree.rs
1
264
264
Implement a Rust struct `FenwickTree` that acts as a Fenwick Tree (Binary Indexed Tree) with 1-based internal indexing and a 0-based public API. The generic type `T` must satisfy `Add<Output = T> + AddAssign + Sub<Output = T> + SubAssign + Copy + Default`. The struct should store a `Vec<T>` where the first element is u...
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. /// Thi...
nvidia/nemotron-3.5-lightning-30b-a3b
da91b964aff5947c-0
da91b964aff5947c
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/optimal_bst.rs
file
optimal_bst.rs
src/dynamic_programming/optimal_bst.rs
1
93
93
I need a Rust function `optimal_search_tree` that takes a `&[i32]` of key access frequencies and returns the minimum possible search cost of an Optimal Binary Search Tree. The solution must use dynamic programming with O(n^3) time and O(n^2) space, building a DP table and a prefix sum array over the frequencies. For ea...
// 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 fr...
nvidia/nemotron-3.5-lightning-30b-a3b
b9165b63d41e9efd-0
b9165b63d41e9efd
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/ciphers/chacha.rs
file
chacha.rs
src/ciphers/chacha.rs
1
150
150
I need a Rust implementation of the ChaCha20 stream cipher following RFC8439. The code should define a `quarter_round!` macro that operates on four 32-bit unsigned integers using wrapping addition and rotate-left operations, and a public `chacha20` function with signature `chacha20(input: &[u32; 16], output: &mut [u32;...
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...
nvidia/nemotron-3.5-lightning-30b-a3b
833f1735183b763d-0
833f1735183b763d
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/rod_cutting.rs
file
rod_cutting.rs
src/dynamic_programming/rod_cutting.rs
1
65
65
I need a Rust function named `rod_cut` that computes the maximum profit from cutting a rod given a slice of prices, where `prices[i]` is the price for a piece of length `i+1`. The function should take `&[usize]` and return `usize`, handle empty input by returning 0, and use dynamic programming with O(n^2) time and O(n)...
//! 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 //...
nvidia/nemotron-3.5-lightning-30b-a3b
a89974ac751868c4-0
a89974ac751868c4
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/minimum_cost_path.rs
file
minimum_cost_path.rs
src/dynamic_programming/minimum_cost_path.rs
1
177
177
I need a Rust function `minimum_cost_path` that computes the minimum cost path from the top-left to the bottom-right of a matrix, moving only right or down. The input is `Vec<Vec<usize>>` and the output is `Result<usize, MatrixError>`. I also need a `MatrixError` enum with variants `EmptyMatrix` and `NonRectangularMatr...
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 i...
nvidia/nemotron-3.5-lightning-30b-a3b
8b7dff2f6c5a6714-0
8b7dff2f6c5a6714
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/matrix_chain_multiply.rs
file
matrix_chain_multiply.rs
src/dynamic_programming/matrix_chain_multiply.rs
1
91
91
I need a Rust implementation of a dynamic programming function `matrix_chain_multiply` that computes the minimum number of scalar multiplications for a matrix chain given a `Vec<usize>` of dimensions. The function should return `Result<usize, MatrixChainMultiplicationError>`, where the error enum has variants `EmptyDim...
//! 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 c...
nvidia/nemotron-3.5-lightning-30b-a3b
5436a724fca948f6-0
5436a724fca948f6
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/subset_sum.rs
file
subset_sum.rs
src/dynamic_programming/subset_sum.rs
1
81
81
Write a Rust function `is_sum_subset` that determines if a subset of a given integer array sums to a target value using dynamic programming. The function should accept `arr: &[i32]` and `required_sum: i32`, return `bool`, and handle edge cases: when `required_sum` is 0, return true (empty subset); when the array is emp...
//! 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 th...
nvidia/nemotron-3.5-lightning-30b-a3b
31dfe8a53d85bdbd-0
31dfe8a53d85bdbd
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/word_break.rs
file
word_break.rs
src/dynamic_programming/word_break.rs
1
89
89
I need a Rust function `word_break` that takes a string `s` and a `&[&str]` dictionary and returns `bool` indicating whether `s` can be segmented into a space-separated sequence of one or more dictionary words. The implementation must use a Trie (from `crate::data_structures::Trie<char, bool>`) to store the dictionary ...
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` - `...
nvidia/nemotron-3.5-lightning-30b-a3b
59dd8aa5b5444cf5-0
59dd8aa5b5444cf5
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/trapped_rainwater.rs
file
trapped_rainwater.rs
src/dynamic_programming/trapped_rainwater.rs
1
125
125
I need a Rust module that calculates the total trapped rainwater volume from an elevation map given as a slice of u32. The module must expose a public function `trapped_rainwater(elevation_map: &[u32]) -> u32` that computes trapped water by first determining left-to-right and right-to-left maximum heights via a `calcul...
//! 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 t...
nvidia/nemotron-3.5-lightning-30b-a3b
46200ae7fe9c8f46-0
46200ae7fe9c8f46
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/task_assignment.rs
file
task_assignment.rs
src/dynamic_programming/task_assignment.rs
1
119
119
Write a Rust function `count_task_assignments` that counts valid task-person assignments using bitmask DP. Input: `task_performed: Vec<Vec<usize>>` (1-indexed capable tasks per person) and `total_tasks: usize`. Output: `i64` count of all valid assignments where each person gets exactly one task they can perform and eac...
// 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 pe...
nvidia/nemotron-3.5-lightning-30b-a3b
89aabf42228676d6-0
89aabf42228676d6
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/general/fisher_yates_shuffle.rs
file
fisher_yates_shuffle.rs
src/general/fisher_yates_shuffle.rs
1
25
25
I need a Rust function that performs an in-place Fisher-Yates shuffle on a mutable slice of i32 values. The implementation should use a PCG32 random number generator from the project's math module, seeded with the current system time, with a fallback to a default constant if the time read fails. The function should ite...
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)...
nvidia/nemotron-3.5-lightning-30b-a3b
cfc631b934ba847b-0
cfc631b934ba847b
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/dynamic_programming/maximum_subarray.rs
file
maximum_subarray.rs
src/dynamic_programming/maximum_subarray.rs
1
82
82
Write a Rust module implementing a function maximum_subarray that takes &[isize] and returns the maximum contiguous subarray sum as Result<isize, MaximumSubarrayError>, where MaximumSubarrayError is a custom error type with variant EmptyArray for empty input. The function must use dynamic programming (Kadane's algorith...
//! 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 { ...
nvidia/nemotron-3.5-lightning-30b-a3b
5e4cdb1271a1edb4-0
5e4cdb1271a1edb4
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/financial/equated_monthly_installments.rs
file
equated_monthly_installments.rs
src/financial/equated_monthly_installments.rs
1
87
87
I need a Rust function to calculate the Equated Monthly Installment (EMI) for a loan. The function should accept the principal amount, annual interest rate as a decimal, and the loan term in years. It must implement the standard EMI formula A = p * r * (1 + r)^n / ((1 + r)^n - 1), where r is the monthly interest rate (...
//! Calculates the Equated Monthly Installment (EMI) for a loan. //! //! Formula: A = p * r * (1 + r)^n / ((1 + r)^n - 1) //! where: //! - `p` is the principal //! - `r` is the monthly interest rate (annual rate / 12) //! - `n` is the total number of monthly payments (years * 12) //! //! Wikipedia Reference: http...
nvidia/nemotron-3.5-lightning-30b-a3b
4016675064b24ee3-0
4016675064b24ee3
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/general/two_sum.rs
file
two_sum.rs
src/general/two_sum.rs
1
65
65
Write a Rust function named `two_sum` that takes a `Vec<i32>` and an `i32` target, and returns `Option<(usize, usize)>`. The function should find two distinct indices in the vector whose values sum to the target, using a single-pass hash map for efficient lookup. If no such pair exists, it should return `None`. The imp...
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...
nvidia/nemotron-3.5-lightning-30b-a3b
c29298385dc8c9d9-0
c29298385dc8c9d9
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/general/mod.rs
file
mod.rs
src/general/mod.rs
1
27
27
I need a Rust module file `mod.rs` that organizes multiple algorithm submodules and re-exports their public API. The file should declare submodules for several algorithms: convex hull, Fisher-Yates shuffle, genetic algorithm, Tower of Hanoi, Huffman encoding, Kadane's algorithm, K-means clustering, MEX calculation, per...
mod convex_hull; mod fisher_yates_shuffle; mod genetic; mod hanoi; mod huffman_encoding; mod kadane_algorithm; mod kmeans; mod mex; mod permutations; mod subarray_sum_equals_k; mod two_sum; pub use self::convex_hull::convex_hull_graham; pub use self::fisher_yates_shuffle::fisher_yates_shuffle; pub use self::genetic::G...
nvidia/nemotron-3.5-lightning-30b-a3b
e315012ca3c2692e-0
e315012ca3c2692e
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/general/hanoi.rs
file
hanoi.rs
src/general/hanoi.rs
1
21
21
I need a Rust function named `hanoi` that implements the Tower of Hanoi algorithm. It should accept `n: i32` (number of disks), three `i32` peg identifiers named `from`, `to`, and `via`, and a mutable reference to a vector of tuples `moves: &mut Vec<(i32, i32)>` that records each disk move. The function must recursivel...
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...
nvidia/nemotron-3.5-lightning-30b-a3b
a4ca54a6992a5a46-0
a4ca54a6992a5a46
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/financial/mod.rs
file
mod.rs
src/financial/mod.rs
1
26
26
I need a Rust source file that defines several financial calculation modules and re-exports their main functions at the crate level. The file should declare submodules named depreciation, equated_monthly_installments, exponential_moving_average, finance_ratios, interest, npv, npv_sensitivity, payback, present_value, an...
mod depreciation; mod equated_monthly_installments; mod exponential_moving_average; mod finance_ratios; mod interest; mod npv; mod npv_sensitivity; mod payback; mod present_value; mod treynor_ratio; pub use self::depreciation::{ diminishing_balance_depreciation, double_declining_balance_depreciation, straight_...
nvidia/nemotron-3.5-lightning-30b-a3b
460c42ac8cc06dfa-0
460c42ac8cc06dfa
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/graph/detect_cycle.rs
file
detect_cycle.rs
src/graph/detect_cycle.rs
1
294
294
I need a Rust implementation of a DetectCycle trait for UndirectedGraph and DirectedGraph types from a graph data structures crate. The trait should expose detect_cycle_dfs and detect_cycle_bfs methods both returning bool. The undirected DFS helper should traverse the adjacency table using a visited HashSet<&String> an...
use std::collections::{HashMap, HashSet, VecDeque}; use crate::data_structures::{graph::Graph, DirectedGraph, UndirectedGraph}; pub trait DetectCycle { fn detect_cycle_dfs(&self) -> bool; fn detect_cycle_bfs(&self) -> bool; } // Helper function to detect cycle in an undirected graph using DFS graph traversal...
nvidia/nemotron-3.5-lightning-30b-a3b
2bba6087f661af5a-0
2bba6087f661af5a
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/geometry/mod.rs
file
mod.rs
src/geometry/mod.rs
1
15
15
I need a Rust module file for a geometry crate that re-exports public types and functions from several submodules. Please write a mod.rs file that uses pub use self:: statements to re-export closest_points from closest_points, graham_scan from graham_scan, jarvis_march from jarvis_scan, Point from point, lattice_points...
mod closest_points; mod graham_scan; mod jarvis_scan; mod point; mod polygon_points; mod ramer_douglas_peucker; mod segment; pub use self::closest_points::closest_points; pub use self::graham_scan::graham_scan; pub use self::jarvis_scan::jarvis_march; pub use self::point::Point; pub use self::polygon_points::lattice_p...
nvidia/nemotron-3.5-lightning-30b-a3b
9b3e661ec37e3b5e-0
9b3e661ec37e3b5e
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/graph/dinic_maxflow.rs
file
dinic_maxflow.rs
src/graph/dinic_maxflow.rs
1
213
213
I need a Rust module that implements Dinic's maximum flow algorithm. Define a `FlowEdge<T>` struct with `sink`, `capacity`, and `flow` fields, and a `FlowResultEdge<T>` struct with `source`, `sink`, and `flow`. Create a `DinicMaxFlow<T>` struct where vertices are numbered from 1 to `n`, supporting `new(source, sink, nu...
use std::collections::VecDeque; use std::ops::{Add, AddAssign, Neg, Sub, SubAssign}; // We assume that graph vertices are numbered from 1 to n. /// Adjacency matrix type Graph = Vec<Vec<usize>>; /// We assume that T::default() gives "zero" flow and T supports negative values pub struct FlowEdge<T> { pub sink: us...
nvidia/nemotron-3.5-lightning-30b-a3b
5c9ca890f7129c6d-0
5c9ca890f7129c6d
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/graph/disjoint_set_union.rs
file
disjoint_set_union.rs
src/graph/disjoint_set_union.rs
1
148
148
I need a Rust module implementing a Disjoint Set Union (Union-Find) data structure. It should include a `DSUNode` struct with `parent` and `size` fields, and a `DisjointSetUnion` struct that manages a collection of such nodes. The module must provide a `new` function initializing each element as its own root, a `find_s...
//! This module implements the Disjoint Set Union (DSU), also known as Union-Find, //! which is an efficient data structure for keeping track of a set of elements //! partitioned into disjoint (non-overlapping) subsets. /// Represents a node in the Disjoint Set Union (DSU) structure which /// keep track of the parent...
nvidia/nemotron-3.5-lightning-30b-a3b
9f2cadce04601bcf-0
9f2cadce04601bcf
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/geometry/point.rs
file
point.rs
src/geometry/point.rs
1
38
38
I need a Rust `Point` struct with `f64` fields `x` and `y`, a public constructor `new(x: f64, y: f64)`, a method `cross_prod(&self, other: &Point) -> f64` that returns the 2D cross product of this point with another, a method `euclidean_distance(&self, other: &Point) -> f64` that computes the Euclidean distance to anot...
use std::ops::Sub; #[derive(Clone, Debug, PartialEq)] pub struct Point { pub x: f64, pub y: f64, } impl Point { pub fn new(x: f64, y: f64) -> Point { Point { x, y } } // Returns the orientation of consecutive segments ab and bc. pub fn consecutive_orientation(&self, b: &Point, c: &Poi...
nvidia/nemotron-3.5-lightning-30b-a3b
3c5c722a255417bb-0
3c5c722a255417bb
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/graph/minimum_spanning_tree.rs
file
minimum_spanning_tree.rs
src/graph/minimum_spanning_tree.rs
1
159
159
Write a Rust module that implements Kruskal's algorithm to find the Minimum Spanning Tree of an undirected, weighted graph. The module should define a struct `Edge` with `source`, `destination`, and `cost` fields, and a function `kruskal` that takes a `Vec<Edge>` and `num_vertices: usize`, returning `Option<(usize, Vec...
//! This module implements Kruskal's algorithm to find the Minimum Spanning Tree (MST) //! of an undirected, weighted graph using a Disjoint Set Union (DSU) for cycle detection. use crate::graph::DisjointSetUnion; /// Represents an edge in the graph with a source, destination, and associated cost. #[derive(Debug, Par...
nvidia/nemotron-3.5-lightning-30b-a3b
fb0d4f67a9c99dde-0
fb0d4f67a9c99dde
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/graph/lowest_common_ancestor.rs
file
lowest_common_ancestor.rs
src/graph/lowest_common_ancestor.rs
1
211
211
I need a Rust module for lowest common ancestor queries on a rooted tree where vertices are numbered 1 to n. The module should provide two implementations: an online LCA using sparse tables (binary lifting) with O(n log n) preprocessing and O(log n) per-query time, and an offline LCA using Tarjan's DSU-based algorithm ...
/* Note: We will assume that here tree vertices are numbered from 1 to n. If a tree is not enumerated that way or its vertices are not represented using numbers, it can trivially be converted using Depth First Search manually or by using `src/graph/graph_enumeration.rs` Here we implement two different algorithms: - ...
nvidia/nemotron-3.5-lightning-30b-a3b
404375954e266a44-0
404375954e266a44
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/financial/npv_sensitivity.rs
file
npv_sensitivity.rs
src/financial/npv_sensitivity.rs
1
43
43
Write a Rust function named `npv_sensitivity` that computes the Net Present Value (NPV) of a cash flow series at multiple discount rates to show sensitivity. The function should accept two arguments: `cash_flows`, a slice of `f64` where each entry is a period value (e.g., year 0 is the initial investment, year 1+ are r...
/// 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...
nvidia/nemotron-3.5-lightning-30b-a3b
387d7a670478b37f-0
387d7a670478b37f
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/greedy/mod.rs
file
mod.rs
src/greedy/mod.rs
1
9
9
I need a Rust module file for a greedy algorithms package that declares four submodules—job_sequencing, minimum_coin_change, smallest_range, and stable_matching—and re-exports schedule_jobs, Job, and ScheduleResult from job_sequencing; find_minimum_change from minimum_coin_change; smallest_range from smallest_range; an...
mod job_sequencing; mod minimum_coin_change; mod smallest_range; mod stable_matching; pub use self::job_sequencing::{schedule_jobs, Job, ScheduleResult}; pub use self::minimum_coin_change::find_minimum_change; pub use self::smallest_range::smallest_range; pub use self::stable_matching::stable_matching;
nvidia/nemotron-3.5-lightning-30b-a3b
fced7ddde9f0e508-0
fced7ddde9f0e508
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/graph/prufer_code.rs
file
prufer_code.rs
src/graph/prufer_code.rs
1
127
127
I need a Rust module that implements Prüfer code encoding and decoding for labeled trees. Write a function `prufer_encode` that takes a reference to a `Graph<V>` (where `Graph<V> = BTreeMap<V, Vec<V>>` and `V: Ord + Copy`) and returns a `Vec<V>` representing the Prüfer sequence. The function should handle trees with mo...
use std::collections::{BTreeMap, BTreeSet, BinaryHeap}; type Graph<V> = BTreeMap<V, Vec<V>>; pub fn prufer_encode<V: Ord + Copy>(tree: &Graph<V>) -> Vec<V> { if tree.len() <= 2 { return vec![]; } let mut result: Vec<V> = Vec::with_capacity(tree.len() - 2); let mut queue = BinaryHeap::new(); ...
nvidia/nemotron-3.5-lightning-30b-a3b
ccbaf249051d4bb0-0
ccbaf249051d4bb0
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/hashing/hashing_traits.rs
file
hashing_traits.rs
src/hashing/hashing_traits.rs
1
67
67
I'm looking to implement an RFC 2104 HMAC in Rust. I need a generic `Hasher` trait parameterized by digest size with methods to create a new default instance, feed data incrementally, and retrieve the current hash. Then I need an `HMAC` struct that takes a key length, digest length, and a hasher type conforming to that...
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 necessary does finalization work /// on the instance, thus it may no longer m...
nvidia/nemotron-3.5-lightning-30b-a3b
945c659309b63d7f-0
945c659309b63d7f
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/graph/tarjans_ssc.rs
file
tarjans_ssc.rs
src/graph/tarjans_ssc.rs
1
173
173
I need a Rust module that defines a `Graph` struct and implements Tarjan's strongly connected components algorithm. The `Graph` struct should have a field `n: usize` and an adjacency list `adj_list: Vec<Vec<usize>>`, with a public constructor `Graph::new(n: usize)` that initializes the adjacency list for `n` vertices, ...
pub struct Graph { n: usize, adj_list: Vec<Vec<usize>>, } impl Graph { pub fn new(n: usize) -> Self { Self { n, adj_list: vec![vec![]; n], } } pub fn add_edge(&mut self, u: usize, v: usize) { self.adj_list[u].push(v); } } pub fn tarjan_scc(graph:...
nvidia/nemotron-3.5-lightning-30b-a3b
156503221ed26a4b-0
156503221ed26a4b
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/lib.rs
file
lib.rs
src/lib.rs
1
22
22
I need a Rust library root file that declares public submodules for every major algorithm category in the project. Please generate the content that uses `pub mod` to include each of the following: backtracking, big_integer, bit_manipulation, ciphers, compression, conversions, data_structures, dynamic_programming, finan...
pub mod backtracking; pub mod big_integer; pub mod bit_manipulation; pub mod ciphers; pub mod compression; pub mod conversions; pub mod data_structures; pub mod dynamic_programming; pub mod financial; pub mod general; pub mod geometry; pub mod graph; pub mod greedy; pub mod hashing; pub mod machine_learning; pub mod ma...
nvidia/nemotron-3.5-lightning-30b-a3b
92344198abb8977f-0
92344198abb8977f
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/hashing/mod.rs
file
mod.rs
src/hashing/mod.rs
1
15
15
Write a Rust module that declares submodules for blake2b, fletcher, hashing_traits, md5, sha1, sha2, and sha3, and re-exports their public functions and types: blake2b from blake2b, fletcher from fletcher, Hasher and HMAC from hashing_traits, md5 and md5_hex from md5, sha1 from sha1, and sha224, sha256, sha384, sha512,...
mod blake2b; mod fletcher; mod hashing_traits; mod md5; mod sha1; mod sha2; mod sha3; pub use self::blake2b::blake2b; pub use self::fletcher::fletcher; pub use self::hashing_traits::{Hasher, HMAC}; pub use self::md5::{md5, md5_hex}; pub use self::sha1::sha1; pub use self::sha2::{sha224, sha256, sha384, sha512, sha512_...
nvidia/nemotron-3.5-lightning-30b-a3b
d45ad1c82f8e7b57-0
d45ad1c82f8e7b57
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/hashing/sha3.rs
file
sha3.rs
src/hashing/sha3.rs
1
590
590
I need a Rust module that implements the SHA-3 hash functions (sha3-224, sha3-256, sha3-384, sha3-512) using the Keccak-f[1600] permutation. The implementation must include the internal state manipulation functions (theta, rho, pi, chi, iota), the Keccak-f permutation on a 5x5xW state array, 10*1 padding, sponge constr...
/// 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 { ...
nvidia/nemotron-3.5-lightning-30b-a3b
c694594525072b81-0
c694594525072b81
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/hashing/blake2b.rs
file
blake2b.rs
src/hashing/blake2b.rs
1
318
318
Implement a Rust function `blake2b` that computes the BLAKE2b hash as specified in RFC 7693. The function should accept three parameters: a message slice `m: &[u8]`, an optional key `k: &[u8]` up to 64 bytes, and an output length parameter `nn: u8` between 1 and 64 inclusive. It must return a `Vec<u8>` containing exact...
// 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...
nvidia/nemotron-3.5-lightning-30b-a3b
5b05b4a21411dd2f-0
5b05b4a21411dd2f
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/machine_learning/loss_function/huber_loss.rs
file
huber_loss.rs
src/machine_learning/loss_function/huber_loss.rs
1
74
74
I need a Rust function that computes the Huber loss between two slices of `f64` values. The function, named `huber_loss`, takes `y_true: &[f64]`, `y_pred: &[f64]`, and a `delta: f64`. It returns `Option<f64>`, where `None` is returned if the slices have different lengths or if the predicted slice is empty. The loss for...
/// 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 ...
nvidia/nemotron-3.5-lightning-30b-a3b
9d387dc6f997ca00-0
9d387dc6f997ca00
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/machine_learning/k_means.rs
file
k_means.rs
src/machine_learning/k_means.rs
1
90
90
I need a Rust function named `k_means` that implements the k-means clustering algorithm for a set of 2D points. The function should accept `data_points: Vec<(f64, f64)>`, `n_clusters: usize`, and `max_iter: i32`. It should randomly initialize `n_clusters` centroids using `rand::random`, assign each data point to the ne...
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()...
nvidia/nemotron-3.5-lightning-30b-a3b
315064e3decf2fc5-0
315064e3decf2fc5
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/machine_learning/loss_function/mean_absolute_error_loss.rs
file
mean_absolute_error_loss.rs
src/machine_learning/loss_function/mean_absolute_error_loss.rs
1
36
36
I need a Rust function named `mae_loss` that computes the Mean Absolute Error loss given two `&[f64]` slices for predicted and actual values. The function should zip the two slices, accumulate the absolute differences of corresponding elements, and return the average as an `f64` by dividing the total by the number of e...
//! # 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 los...
nvidia/nemotron-3.5-lightning-30b-a3b
c808ec8e16ae313f-0
c808ec8e16ae313f
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/machine_learning/loss_function/mean_squared_error_loss.rs
file
mean_squared_error_loss.rs
src/machine_learning/loss_function/mean_squared_error_loss.rs
1
35
35
I need a Rust function named `mse_loss` that calculates the mean squared error loss between two slices of floating-point numbers. The function should accept two parameters: `predicted: &[f64]` and `actual: &[f64]`, and return an `f64` representing the average squared difference. The implementation should iterate over z...
//! # 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 calcula...
nvidia/nemotron-3.5-lightning-30b-a3b
f7f3d3ae23d4e046-0
f7f3d3ae23d4e046
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/machine_learning/loss_function/kl_divergence_loss.rs
file
kl_divergence_loss.rs
src/machine_learning/loss_function/kl_divergence_loss.rs
1
37
37
I need a Rust function `kld_loss` that computes the KL divergence loss between two probability distribution slices. It should accept two references to `f64` slices named `actual` and `predicted`, and return an `f64`. The implementation must smooth each element with a small epsilon `0.00001f64` to prevent logarithm of z...
//! # 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 natu...
nvidia/nemotron-3.5-lightning-30b-a3b
9ed60a0236dcbbee-0
9ed60a0236dcbbee
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/machine_learning/loss_function/hinge_loss.rs
file
hinge_loss.rs
src/machine_learning/loss_function/hinge_loss.rs
1
38
38
Write a Rust function named `hng_loss` that takes two `&[f64]` slices (`y_true` and `y_pred`), zips them together, computes `max(0.0, 1.0 - y_true * y_pred)` for each pair, accumulates the loss, and returns the average as an `f64` by dividing by the number of elements. The function has no explicit error handling.
//! # 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: //! //! ...
nvidia/nemotron-3.5-lightning-30b-a3b
36d25c65763dbac0-0
36d25c65763dbac0
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/machine_learning/loss_function/mod.rs
file
mod.rs
src/machine_learning/loss_function/mod.rs
1
15
15
I need a Rust module file that declares seven submodules for machine learning loss functions: average_margin_ranking_loss, hinge_loss, huber_loss, kl_divergence_loss, mean_absolute_error_loss, mean_squared_error_loss, and negative_log_likelihood. After each mod declaration, the file should re-export the primary functio...
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_lo...
nvidia/nemotron-3.5-lightning-30b-a3b
f8807c2d6b60d851-0
f8807c2d6b60d851
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/catalan_numbers.rs
file
catalan_numbers.rs
src/math/catalan_numbers.rs
1
59
59
Write a Rust function called `init_catalan` that precomputes Catalan numbers up to index 1005 modulo 1_000_000_007 using dynamic programming. The function should return a `Vec<i64>` where each element at index `i` is the i-th Catalan number modulo the given modulus, computed with the recurrence C[i] = sum_{j=0}^{i-1} C...
// Introduction to Catalan Numbers: // Catalan numbers are a sequence of natural numbers with many applications in combinatorial mathematics. // They are named after the Belgian mathematician Eugène Charles Catalan, who contributed to their study. // Catalan numbers appear in various combinatorial problems, including c...
nvidia/nemotron-3.5-lightning-30b-a3b
d520cc5b05f002a4-0
d520cc5b05f002a4
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/machine_learning/optimization/mod.rs
file
mod.rs
src/machine_learning/optimization/mod.rs
1
6
6
Write a Rust module file that declares submodules for `adam`, `gradient_descent`, and `momentum`, and re-exports the `Adam` type and `gradient_descent` function.
mod adam; mod gradient_descent; mod momentum; pub use self::adam::Adam; pub use self::gradient_descent::gradient_descent;
nvidia/nemotron-3.5-lightning-30b-a3b
35f2546c0c7d587f-0
35f2546c0c7d587f
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/chinese_remainder_theorem.rs
file
chinese_remainder_theorem.rs
src/math/chinese_remainder_theorem.rs
1
35
35
I need a Rust function that implements the Chinese Remainder Theorem. It should take two slices, `residues: &[i32]` and `modulli: &[i32]`, and return `Option<i32>` — the unique solution modulo the product of all moduli, or `None` if a modular inverse cannot be computed because the greatest common divisor of the partial...
use super::extended_euclidean_algorithm; fn mod_inv(x: i32, n: i32) -> Option<i32> { let (g, x, _) = extended_euclidean_algorithm(x, n); if g == 1 { Some((x % n + n) % n) } else { None } } pub fn chinese_remainder_theorem(residues: &[i32], modulli: &[i32]) -> Option<i32> { let prod...
nvidia/nemotron-3.5-lightning-30b-a3b
145aa9057ec1df4f-0
145aa9057ec1df4f
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/exponential_linear_unit.rs
file
exponential_linear_unit.rs
src/math/exponential_linear_unit.rs
1
60
60
I need a Rust function named `exponential_linear_unit` that takes a `&Vec<f64>` and an `f64` alpha parameter, and returns a new `Vec<f64>` applying the Exponential Linear Unit activation: for each element, if it is non-negative the value is kept unchanged, if it is negative it becomes `alpha * (e^x - 1)` using `std::f6...
//! # Exponential Linear Unit (ELU) Function //! //! The `exponential_linear_unit` function computes the Exponential Linear Unit (ELU) values of a given vector //! of f64 numbers with a specified alpha parameter. //! //! The ELU activation function is commonly used in neural networks as an alternative to the Leaky ReLU...
nvidia/nemotron-3.5-lightning-30b-a3b
33a7d16dddf6ee9e-0
33a7d16dddf6ee9e
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/amicable_numbers.rs
file
amicable_numbers.rs
src/math/amicable_numbers.rs
1
68
68
Write a Rust function `amicable_pairs_under_n` that takes a positive `u32` argument `n` and returns `Option<Vec<(u32, u32)>>` containing all amicable pairs (a, b) strictly below `n` with `a < b`, where the sum of proper divisors of `a` equals `b` and vice versa. The implementation should use an efficient sieve-like met...
// Operations based around amicable numbers // Suports u32 but should be interchangable with other types // Wikipedia reference: https://en.wikipedia.org/wiki/Amicable_numbers // Returns vec of amicable pairs below N // N must be positive pub fn amicable_pairs_under_n(n: u32) -> Option<Vec<(u32, u32)>> { let mut f...
nvidia/nemotron-3.5-lightning-30b-a3b
a9de44807f67e770-0
a9de44807f67e770
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/cross_entropy_loss.rs
file
cross_entropy_loss.rs
src/math/cross_entropy_loss.rs
1
40
40
I need a Rust function named `cross_entropy_loss` that takes two `&[f64]` slices—`actual` and `predicted`—and returns the cross-entropy loss as `f64` by summing `-a * p.ln()` over zipped pairs. The implementation should use `f64::ln()` for the natural logarithm and `Iterator::sum` to aggregate. Include a test module wi...
//! # Cross-Entropy Loss Function //! //! The `cross_entropy_loss` function calculates the cross-entropy loss between the actual and predicted probability distributions. //! //! Cross-entropy loss is commonly used in machine learning and deep learning to measure the dissimilarity between two probability distributions. ...
nvidia/nemotron-3.5-lightning-30b-a3b
d3cc57d5d7d98253-0
d3cc57d5d7d98253
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/euclidean_distance.rs
file
euclidean_distance.rs
src/math/euclidean_distance.rs
1
41
41
I need a Rust function named `euclidean_distance` that calculates the Euclidean distance between two vectors of floating-point numbers. The function should take two references to a type alias `Vector` (which is `Vec<f64>`), compute the sum of squared differences between corresponding elements using an iterator, and ret...
// Author : cyrixninja // Calculate the Euclidean distance between two vectors // Wikipedia : https://en.wikipedia.org/wiki/Euclidean_distance pub fn euclidean_distance(vector_1: &Vector, vector_2: &Vector) -> f64 { // Calculate the Euclidean distance using the provided vectors. let squared_sum: f64 = vector_1...
nvidia/nemotron-3.5-lightning-30b-a3b
656d3782b8e56283-0
656d3782b8e56283
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/graph/mod.rs
file
mod.rs
src/graph/mod.rs
1
59
59
Write a Rust module file for a graph crate that declares submodules for a collection of graph algorithms and re-exports their public APIs. The file should declare modules named ant_colony_optimization, astar, bellman_ford, bipartite_matching, breadth_first_search, centroid_decomposition, decremental_connectivity, depth...
mod ant_colony_optimization; mod astar; mod bellman_ford; mod bipartite_matching; mod breadth_first_search; mod centroid_decomposition; mod decremental_connectivity; mod depth_first_search; mod depth_first_search_tic_tac_toe; mod detect_cycle; mod dijkstra; mod dinic_maxflow; mod disjoint_set_union; mod eulerian_path; ...
nvidia/nemotron-3.5-lightning-30b-a3b
e463284ebab5d891-0
e463284ebab5d891
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/fast_power.rs
file
fast_power.rs
src/math/fast_power.rs
1
29
29
I need a Rust function called `fast_power` that efficiently computes modular exponentiation using the binary exponentiation algorithm. It should accept three `usize` arguments: `base`, `power`, and `modulus`, and return `usize`. The implementation must include an assertion that `base >= 1`, and use a `while power > 0` ...
/// fast_power returns the result of base^power mod modulus pub fn fast_power(mut base: usize, mut power: usize, modulus: usize) -> usize { assert!(base >= 1); let mut res = 1; while power > 0 { if power & 1 == 1 { res = (res * base) % modulus; } base = (base * base) % m...
nvidia/nemotron-3.5-lightning-30b-a3b
6987d52ab31c1ae9-0
6987d52ab31c1ae9
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/machine_learning/mod.rs
file
mod.rs
src/machine_learning/mod.rs
1
30
30
I need a Rust module file that serves as the main module for a machine learning crate. It should declare submodules named cholesky, decision_tree, k_means, k_nearest_neighbors, linear_regression, logistic_regression, loss_function, naive_bayes, optimization, perceptron, principal_component_analysis, random_forest, and ...
mod cholesky; mod decision_tree; mod k_means; mod k_nearest_neighbors; mod linear_regression; mod logistic_regression; mod loss_function; mod naive_bayes; mod optimization; mod perceptron; mod principal_component_analysis; mod random_forest; mod support_vector_classifier; pub use self::cholesky::cholesky; pub use self...
nvidia/nemotron-3.5-lightning-30b-a3b
3d3c7e709ffca766-0
3d3c7e709ffca766
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/extended_euclidean_algorithm.rs
file
extended_euclidean_algorithm.rs
src/math/extended_euclidean_algorithm.rs
1
37
37
I need a Rust module that implements the extended Euclidean algorithm with a helper function `update_step` and a main function `extended_euclidean_algorithm`. The helper should take mutable references to the current and previous remainders/coefficients and a quotient, updating them in place. The main function should ac...
fn update_step(a: &mut i32, old_a: &mut i32, quotient: i32) { let temp = *a; *a = *old_a - quotient * temp; *old_a = temp; } pub fn extended_euclidean_algorithm(a: i32, b: i32) -> (i32, i32, i32) { let (mut old_r, mut rem) = (a, b); let (mut old_s, mut coeff_s) = (1, 0); let (mut old_t, mut coe...
nvidia/nemotron-3.5-lightning-30b-a3b
081639f2cc5e5e6b-0
081639f2cc5e5e6b
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/collatz_sequence.rs
file
collatz_sequence.rs
src/math/collatz_sequence.rs
1
32
32
I need a Rust function that generates the Collatz sequence for a given non-negative integer. The function should accept a mutable usize input and return Option<Vec<usize>>. If the input is 0, it should return None. For any positive integer, it should produce the sequence starting from the input, applying the Collatz ru...
// collatz conjecture : https://en.wikipedia.org/wiki/Collatz_conjecture pub fn sequence(mut n: usize) -> Option<Vec<usize>> { if n == 0 { return None; } let mut list: Vec<usize> = vec![]; while n != 1 { list.push(n); if n.is_multiple_of(2) { n /= 2; } else { ...
nvidia/nemotron-3.5-lightning-30b-a3b
07982fb9fb0b57a2-0
07982fb9fb0b57a2
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/doomsday.rs
file
doomsday.rs
src/math/doomsday.rs
1
36
36
I need a Rust function that implements the Doomsday algorithm to calculate the day of the week for a given date. The function should accept three i32 arguments: year, month, and day. It should return the weekday as a String (e.g., "Monday"). The implementation must use a constant lookup table for month offsets, adjust ...
const T: [i32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]; pub fn doomsday(y: i32, m: i32, d: i32) -> i32 { let y = if m < 3 { y - 1 } else { y }; (y + y / 4 - y / 100 + y / 400 + T[(m - 1) as usize] + d) % 7 } pub fn get_week_day(y: i32, m: i32, d: i32) -> String { let day = doomsday(y, m, d); let da...
nvidia/nemotron-3.5-lightning-30b-a3b
8a78a14557acdf3c-0
8a78a14557acdf3c
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/frizzy_number.rs
file
frizzy_number.rs
src/math/frizzy_number.rs
1
61
61
I need a Rust function `get_nth_frizzy` that takes a base integer `base` and an index `n`, and returns the n-th Frizzy number as `f64`. The Frizzy number is computed by interpreting the binary representation of `n`: each set bit at position `i` means `base^i` is included in the sum. The function iterates while `n > 0`,...
/// This Rust program calculates the n-th Frizzy number for a given base. /// A Frizzy number is defined as the n-th number that is a sum of powers /// of the given base, with the powers corresponding to the binary representation /// of n. /// The `get_nth_frizzy` function takes two arguments: /// * `base` - The base ...
nvidia/nemotron-3.5-lightning-30b-a3b
4c4552f448e2e514-0
4c4552f448e2e514
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/infix_to_postfix.rs
file
infix_to_postfix.rs
src/math/infix_to_postfix.rs
1
94
94
I need a Rust function `infix_to_postfix` that converts a mathematical expression from infix notation to postfix (Reverse Polish Notation). The function should accept a `&str` and return a `Result<String, InfixToPostfixError>`. I also need a custom error enum `InfixToPostfixError` with variants `UnknownCharacter(char)`...
#[derive(Debug, Clone, PartialEq, Eq)] pub enum InfixToPostfixError { UnknownCharacter(char), UnmatchedParent, } /// Function to convert [infix expression](https://en.wikipedia.org/wiki/Infix_notation) to [postfix expression](https://en.wikipedia.org/wiki/Reverse_Polish_notation) pub fn infix_to_postfix(infix:...
nvidia/nemotron-3.5-lightning-30b-a3b
5976d0e632d2f2c5-0
5976d0e632d2f2c5
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/geometric_series.rs
file
geometric_series.rs
src/math/geometric_series.rs
1
49
49
I need a Rust function named geometric_series that computes the first n terms of a geometric series. It should accept three f64 parameters: the number of terms, the starting term, and the common ratio, and return a Vec<f64>. The function should iterate n times (cast from f64 to i32), starting with the initial term and ...
// Author : cyrixninja // Wikipedia : https://en.wikipedia.org/wiki/Geometric_series // Calculate a geometric series. pub fn geometric_series(nth_term: f64, start_term_a: f64, common_ratio_r: f64) -> Vec<f64> { let mut series = Vec::new(); let mut multiple = 1.0; for _ in 0..(nth_term as i32) { se...
nvidia/nemotron-3.5-lightning-30b-a3b
c06fb76a6bf01834-0
c06fb76a6bf01834
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/gcd_of_n_numbers.rs
file
gcd_of_n_numbers.rs
src/math/gcd_of_n_numbers.rs
1
29
29
I need a Rust function `gcd` that computes the greatest common divisor of a slice of unsigned integers. The function should accept `&[usize]` and return `usize`. If the slice contains a single element, return that element. Otherwise, recursively compute the GCD of the first element and the GCD of the rest of the slice....
/// returns the greatest common divisor of n numbers pub fn gcd(nums: &[usize]) -> usize { if nums.len() == 1 { return nums[0]; } let a = nums[0]; let b = gcd(&nums[1..]); gcd_of_two_numbers(a, b) } fn gcd_of_two_numbers(a: usize, b: usize) -> usize { if b == 0 { return a; }...
nvidia/nemotron-3.5-lightning-30b-a3b
ac3bbcfc2402892c-0
ac3bbcfc2402892c
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/gaussian_elimination.rs
file
gaussian_elimination.rs
src/math/gaussian_elimination.rs
1
79
79
I need a Rust function named `gaussian_elimination` that solves a system of linear equations using Gaussian elimination on an augmented matrix. The function should take a mutable reference to a slice of `Vec<f32>` representing an N×(N+1) augmented matrix (N coefficients followed by the constant term), and return a `Vec...
// Gaussian Elimination of Quadratic Matrices // Takes an augmented matrix as input, returns vector of results // Wikipedia reference: augmented matrix: https://en.wikipedia.org/wiki/Augmented_matrix // Wikipedia reference: algorithm: https://en.wikipedia.org/wiki/Gaussian_elimination pub fn gaussian_elimination(matri...
nvidia/nemotron-3.5-lightning-30b-a3b
df44521fc3bf0970-0
df44521fc3bf0970
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/lcm_of_n_numbers.rs
file
lcm_of_n_numbers.rs
src/math/lcm_of_n_numbers.rs
1
30
30
Write a Rust function that computes the least common multiple of a slice of unsigned integers. The function should take `&[usize]` and return `usize`, handle a single-element slice by returning that element, recursively compute the LCM of the remaining elements, and use a helper based on the greatest common divisor of ...
// returns the least common multiple of n numbers pub fn lcm(nums: &[usize]) -> usize { if nums.len() == 1 { return nums[0]; } let a = nums[0]; let b = lcm(&nums[1..]); a * b / gcd_of_two_numbers(a, b) } fn gcd_of_two_numbers(a: usize, b: usize) -> usize { if b == 0 { return a;...
nvidia/nemotron-3.5-lightning-30b-a3b
8a23aebb8e282e6d-0
8a23aebb8e282e6d
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust
fed66cb0c74c4a939ec5163648458a8c2b46fd4c
MIT
src/math/huber_loss.rs
file
huber_loss.rs
src/math/huber_loss.rs
1
43
43
I need a Rust function named `huber_loss` that computes the Huber loss between two slices of floating-point numbers. The function should take `actual` and `predicted` as `&[f64]` references, and a `delta` value of type `f64`. It should return the summed Huber loss as `f64`. For each pair of values, if their absolute di...
//! # Huber Loss Function //! //! The `huber_loss` function calculates the Huber loss, which is a robust loss function used in machine learning, particularly in regression problems. //! //! Huber loss combines the benefits of mean squared error (MSE) and mean absolute error (MAE). It behaves like MSE when the differenc...
nvidia/nemotron-3.5-lightning-30b-a3b