diff --git a/Cargo.toml b/Cargo.toml index 1d6f2b3584d..a646fdede4e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,11 @@ nalgebra = "0.32.3" quickcheck = "1.0" quickcheck_macros = "1.0" +[build-dependencies] +regex = "1.10.3" +syn = "1.0" + + [features] default = ["big-math"] big-math = ["dep:num-bigint", "dep:num-traits"] diff --git a/DIRECTORY.md b/DIRECTORY.md index be77b9ae155..0328b9a31e7 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -18,7 +18,7 @@ * [Another Rot13](https://github.com/TheAlgorithms/Rust/blob/master/src/ciphers/another_rot13.rs) * [Baconian Cipher](https://github.com/TheAlgorithms/Rust/blob/master/src/ciphers/baconian_cipher.rs) * [Base64](https://github.com/TheAlgorithms/Rust/blob/master/src/ciphers/base64.rs) - * [Blake2B](https://github.com/TheAlgorithms/Rust/blob/master/src/ciphers/blake2b.rs) + * [Blake2b](https://github.com/TheAlgorithms/Rust/blob/master/src/ciphers/blake2b.rs) * [Caesar](https://github.com/TheAlgorithms/Rust/blob/master/src/ciphers/caesar.rs) * [Chacha](https://github.com/TheAlgorithms/Rust/blob/master/src/ciphers/chacha.rs) * [Diffie Hellman](https://github.com/TheAlgorithms/Rust/blob/master/src/ciphers/diffie_hellman.rs) @@ -139,7 +139,6 @@ * [Tarjans Ssc](https://github.com/TheAlgorithms/Rust/blob/master/src/graph/tarjans_ssc.rs) * [Topological Sort](https://github.com/TheAlgorithms/Rust/blob/master/src/graph/topological_sort.rs) * [Two Satisfiability](https://github.com/TheAlgorithms/Rust/blob/master/src/graph/two_satisfiability.rs) - * [Lib](https://github.com/TheAlgorithms/Rust/blob/master/src/lib.rs) * Machine Learning * [Cholesky](https://github.com/TheAlgorithms/Rust/blob/master/src/machine_learning/cholesky.rs) * [K Means](https://github.com/TheAlgorithms/Rust/blob/master/src/machine_learning/k_means.rs) @@ -281,12 +280,11 @@ * [Patience Sort](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/patience_sort.rs) * [Pigeonhole Sort](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/pigeonhole_sort.rs) * [Quick Sort](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/quick_sort.rs) - * [Quick Sort 3_ways](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/quick_sort_3_ways.rs) + * [Quick Sort 3 Ways](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/quick_sort_3_ways.rs) * [Radix Sort](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/radix_sort.rs) * [Selection Sort](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/selection_sort.rs) * [Shell Sort](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/shell_sort.rs) * [Sleep Sort](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/sleep_sort.rs) - * [Sort Utils](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/sort_utils.rs) * [Stooge Sort](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/stooge_sort.rs) * [Tim Sort](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/tim_sort.rs) * [Tree Sort](https://github.com/TheAlgorithms/Rust/blob/master/src/sorting/tree_sort.rs) @@ -313,4 +311,4 @@ * [Suffix Array](https://github.com/TheAlgorithms/Rust/blob/master/src/string/suffix_array.rs) * [Suffix Array Manber Myers](https://github.com/TheAlgorithms/Rust/blob/master/src/string/suffix_array_manber_myers.rs) * [Suffix Tree](https://github.com/TheAlgorithms/Rust/blob/master/src/string/suffix_tree.rs) - * [Z Algorithm](https://github.com/TheAlgorithms/Rust/blob/master/src/string/z_algorithm.rs) + * [Z Algorithm](https://github.com/TheAlgorithms/Rust/blob/master/src/string/z_algorithm.rs) \ No newline at end of file diff --git a/build.rs b/build.rs new file mode 100644 index 00000000000..61b550b6c8c --- /dev/null +++ b/build.rs @@ -0,0 +1,607 @@ +use std::{ + fmt::Display, + path::{Path, PathBuf}, +}; +use syn::{Item, UseTree, Visibility::Public}; + +pub fn main() { + use std::{ + fs::{read_to_string, File}, + io::Write, + }; + + // Write exports to mod files. + let mut exports_dir: ExportsDir = ExportsDir::new(Path::new("src")); + exports_dir.write_to_mod_file(); + exports_dir.check_duplicates(); + + // Write the dir and file tree to the DIRECTORY.md file. + let new_contents: String = "# List of all files\n\n##".to_string() + + &UsageTree::new(Path::new("src").to_path_buf()).to_string()[1..]; + let current_contents: String = + read_to_string("DIRECTORY.md").expect("Could not read DIRECTORY.md file"); + if current_contents != new_contents { + File::create("DIRECTORY.md") + .expect("Could not create DIRECTORY.md file") + .write_all(new_contents.as_bytes()) + .expect("Could not write to DIRECTORY.md file"); + } +} + +struct ExportsDir { + pub path: PathBuf, + pub name: String, + pub files: Vec, + pub sub_dirs: Vec, +} +impl ExportsDir { + /// Collect a list of exports in a given directory. Does not recurse. + fn new(directory: &Path) -> ExportsDir { + use std::fs::read_dir; + + let exceptions: [&str; 3] = ["main.rs", "lib.rs", "mod.rs"]; + + // Create initial instance. + let path_buf: PathBuf = directory.to_path_buf(); + let mut exports: ExportsDir = ExportsDir { + path: path_buf.clone(), + name: path_buf + .file_stem() + .unwrap_or_else(|| { + panic!("Could not get filename of path '{}'", path_buf.display()) + }) + .to_str() + .unwrap() + .to_string(), + files: Vec::new(), + sub_dirs: Vec::new(), + }; + + // Populate instance with files and sub-dirs. + let dir_entries = read_dir(directory) + .unwrap_or_else(|_| panic!("Could not read dir {}", directory.display())) + .flatten(); + for dir_entry in dir_entries { + let dir_entry: PathBuf = dir_entry.path(); + if dir_entry.is_dir() { + exports.sub_dirs.push(ExportsDir::new(&dir_entry)); + } else { + let is_exception = exceptions + .iter() + .filter(|exception| dir_entry.ends_with(exception)) + .count() + > 0; + if !is_exception && dir_entry.extension().unwrap() == "rs" { + exports.files.push(ExportsFile::new(dir_entry)); + } + } + } + + // Return instance. + exports + } + + /// Remove some specific exports from all exports in the directory. + pub fn remove_exports(&mut self, exclusions: &Vec) { + for index in (0..self.sub_dirs.len()).rev() { + if exclusions.contains(&self.sub_dirs[index].name) { + self.sub_dirs.remove(index); + } + } + for index in (0..self.files.len()).rev() { + if exclusions.contains(&self.files[index].name) { + self.files.remove(index); + } + } + for sub_dir in &mut self.sub_dirs { + sub_dir.remove_exports(exclusions); + } + for file in &mut self.files { + file.remove_exports(exclusions); + } + } + + /// Prefix all duplicate exports with the name of their file. + pub fn check_duplicates(&mut self) { + for sub_dir in &mut self.sub_dirs { + sub_dir.check_duplicates(); + } + let mut exports_names: Vec<&String> = self + .files + .iter() + .map(|file| &file.name) + .collect::>(); + exports_names.extend_from_slice( + &self + .sub_dirs + .iter() + .map(|sub_dir| &sub_dir.name) + .collect::>()[..], + ); + let mut duplicate_names: Vec = exports_names + .iter() + .enumerate() + .filter(|(index, name)| { + exports_names + .iter() + .position(|compare_name| &compare_name == name) + .unwrap() + != *index + }) + .map(|(_, name)| name.to_string()) + .collect::>(); + duplicate_names.dedup(); + if !duplicate_names.is_empty() { + let mod_file_name: &str = if self.path.join("lib.rs").exists() { + "lib.rs" + } else { + "mod.rs" + }; + panic!( + "'{}' contains duplicate definitions for: {}", + self.path.join(mod_file_name).display(), + duplicate_names.join(", ") + ); + } + } + + /// Remove all files that do not have any exports. + pub fn remove_files_without_exports(&mut self) { + for sub_dir in &mut self.sub_dirs { + sub_dir.remove_files_without_exports(); + } + let indexes_to_remove: Vec = self + .files + .iter() + .enumerate() + .filter(|(_, file)| file.exports.is_empty()) + .map(|(index, _)| index) + .rev() + .collect(); + for index in indexes_to_remove { + self.files.remove(index); + } + } + + /// Write the exports to the mod file. + pub fn write_to_mod_file(&mut self) { + use regex::{Captures, Regex}; + use std::fs::{read_to_string, File}; + use std::io::Write; + + let start_tag_regex: Regex = Regex::new( + r"\/\*\s+auto-exports\s+start\s+(exclusions\=\[(?.+)?\]\s+)?\*\/", + ) + .unwrap(); + let end_tag_regex: Regex = Regex::new(r"\/\*\s+auto-exports\s+end\s+\*\/").unwrap(); + + // Find the output path. + let mut output_path: Option = None; + for addition in &["lib.rs", "mod.rs"] { + let path = self.path.join(addition); + if path.exists() { + output_path = Some(path); + break; + } + } + if output_path.is_none() { + panic!( + "Could not find lib.rs or mod.rs file in dir '{}'", + self.path.display() + ); + } + let output_path: PathBuf = output_path.unwrap(); + + // Validate mod file exists. + if !output_path.exists() { + panic!("Mod file '{}' does not exist.", output_path.display()); + } + if output_path.to_path_buf().is_dir() { + panic!( + "Cannot pass dir '{}' as mod file.", + output_path.to_path_buf().display() + ); + } + let current_mod_contents: String = read_to_string(&output_path).unwrap_or_default(); + + // Find auto-export start tag. + let start_captures: Vec> = start_tag_regex + .captures_iter(¤t_mod_contents) + .collect(); + if start_captures.is_empty() { + return; + } + if start_captures.len() > 1 { + panic!( + "file '{}' has multiple auto-export start tags, which is not supported.", + output_path.display() + ); + } + + let start_capture = &start_captures[0]; + let start_capture_position: usize = start_capture.get(0).unwrap().end(); + let start_tag: &str = start_capture.get(0).unwrap().as_str(); + let exports_prefix: &str = ¤t_mod_contents[..start_capture.get(0).unwrap().start()]; + let export_exclusions: Vec = start_capture + .name("exclusions") + .map(|capture_match| capture_match.as_str()) + .unwrap_or_default() + .split(',') + .map(|exclusion| exclusion.trim().to_string()) + .collect(); + + // Find auto-export end-tag. + let end_captures: Vec> = end_tag_regex + .captures_iter(¤t_mod_contents[start_capture_position..]) + .collect(); + if end_captures.is_empty() { + panic!("Could not find auto-export end tag in file '{}', please add \"/* auto-exports end */\" somewhere.", output_path.display()); + } + if end_captures.len() > 1 { + panic!( + "file '{}' has multiple auto-export end tags, which is not supported.", + output_path.display() + ); + } + let end_capture = &end_captures[0]; + let end_capture_position: usize = + start_capture_position + end_capture.get(0).unwrap().end(); + let end_tag: &str = end_capture.get(0).unwrap().as_str(); + let exports_suffix: &str = if end_capture_position < current_mod_contents.len() { + ¤t_mod_contents[end_capture_position..] + } else { + "" + }; + + // Fix exclusions and duplicates. + self.remove_exports(&export_exclusions); + self.remove_files_without_exports(); + + // Parse exports into string. + let new_mod_contents: String = format!( + "{}{}\n{}\n{}{}", + if exports_prefix.trim().is_empty() { + "" + } else { + exports_prefix + }, + start_tag, + format!( + "{}\n\n{}\n\n{}", + self.sub_dirs + .iter() + .map(|dir| format!("pub mod {};", dir.name)) + .collect::>() + .join("\n"), + self.files + .iter() + .map(|identity| identity.mod_to_string()) + .collect::>() + .join("\n"), + self.files + .iter() + .map(|identity| identity.exports_to_string()) + .collect::>() + .join("\n"), + ) + .trim(), + end_tag, + if exports_suffix.trim().is_empty() { + "\n" + } else { + exports_suffix + } + ); + + // If the new and current contents differ, write to file. + if new_mod_contents != current_mod_contents { + let mut mod_file = File::create(&output_path) + .unwrap_or_else(|_| panic!("Could not access file '{}'", output_path.display())); + mod_file + .write_all(new_mod_contents.as_bytes()) + .unwrap_or_else(|_| panic!("Could not write to file '{}'.", output_path.display())); + } + + // Recurse into sub-dirs. + for dir in &mut self.sub_dirs { + dir.write_to_mod_file(); + } + } +} + +struct ExportsFile { + pub name: String, + pub exports: Vec, +} +impl ExportsFile { + /// Create a new instance. Reads the file and collects exports automatically. + pub fn new(path_buf: PathBuf) -> ExportsFile { + use std::fs::read_to_string; + + // Create the intial instance. + let mut exports_file = ExportsFile { + name: path_buf + .file_stem() + .unwrap_or_else(|| { + panic!("Could not get filename of path '{}'", path_buf.display()) + }) + .to_str() + .unwrap() + .to_string(), + exports: Vec::new(), + }; + + // Find all public exports in the file. + let file_contents: String = read_to_string(&path_buf) + .unwrap_or_else(|_| panic!("Could not read file '{}'", path_buf.display())); + let syntax_tree = syn::parse_file(&file_contents) + .unwrap_or_else(|_| panic!("Could not parse file '{}'", path_buf.display())); + for item in syntax_tree.items { + let identity: Option = match item { + Item::Fn(item) if matches!(item.vis, Public(_)) => Some(item.sig.ident.to_string()), + Item::Struct(item) if matches!(item.vis, Public(_)) => Some(item.ident.to_string()), + Item::Trait(item) if matches!(item.vis, Public(_)) => Some(item.ident.to_string()), + Item::Enum(item) if matches!(item.vis, Public(_)) => Some(item.ident.to_string()), + _ => None, + }; + if let Some(identity) = identity { + exports_file.exports.push(identity); + } + } + + // Return the exports file. + exports_file + } + + /// Remove some specific exports from the file. + pub fn remove_exports(&mut self, removals: &[String]) { + let indexes_to_remove: Vec = self + .exports + .iter() + .enumerate() + .filter(|(_, name)| removals.contains(name)) + .map(|(index, _)| index) + .rev() + .collect::>(); + for index in indexes_to_remove { + self.exports.remove(index); + } + } + + /// Create a string that exports the mod for the mod file. + fn mod_to_string(&self) -> String { + format!("mod {};", self.name) + } + + /// Create a string that uses all exports for the mod file. + fn exports_to_string(&self) -> String { + match self.exports.len() { + 0 => String::new(), + 1 => format!("pub use {}::{};", self.name, self.exports[0]), + _ => format!( + "pub use {}::{}\n\t{}\n{};", + self.name, + '{', + self.exports.join(",\n\t"), + '}' + ), + } + } +} + +struct UsageTree { + path: PathBuf, + name: String, + items: Vec, + sub_trees: Vec, + override_commands: Vec>, +} +impl UsageTree { + /// Create a new exports tree given the starting directory. + pub fn new(dir: PathBuf) -> UsageTree { + use regex::Regex; + use std::fs::read_to_string; + + let directorymd_override: Regex = + Regex::new(r"DIRECTORY\.md override(?([^\S\n]?(\S+))+)").unwrap(); + + if !dir.exists() || !dir.is_dir() { + panic!( + "Could not create UsageTree for directory '{}' as it does not exist.", + dir.display() + ); + } + + // Loop through lib and mod files. + let mut usages: Vec = Vec::new(); + let mut sub_dirs: Vec = Vec::new(); + let mut directory_overrides: Vec> = Vec::new(); + for file_name in ["lib.rs", "mod.rs"] { + let mod_file: PathBuf = dir.join(file_name); + if mod_file.exists() { + // Parse contents. + let file_contents: String = read_to_string(&mod_file) + .unwrap_or_else(|_| panic!("Could not read file '{}'", mod_file.display())); + + // Usage items. + let syntax_tree = syn::parse_file(&file_contents) + .unwrap_or_else(|_| panic!("Could not parse file '{}'", mod_file.display())); + for item in syntax_tree.items { + match &item { + // 'pub use' suggests item in dir. + Item::Use(item) if matches!(item.vis, Public(_)) => { + match &item.tree { + UseTree::Path(path) => usages.push(path.ident.to_string()), + UseTree::Name(name) => usages.push(name.ident.to_string()), + UseTree::Rename(rename) => usages.push(rename.rename.to_string()), + _ => {} + }; + } + + // 'pub mod' suggests sub-dir. + Item::Mod(item) if matches!(item.vis, Public(_)) => { + sub_dirs.push(dir.join(item.ident.to_string())); + } + + _ => {} + } + } + + // Custom DIRECTORY.md overrides. + for capture in directorymd_override.captures_iter(&file_contents) { + let arguments: Vec = capture + .name("arguments") + .unwrap() + .as_str() + .trim() + .to_lowercase() + .split(' ') + .map(|word| word.to_string()) + .collect(); + if !arguments.is_empty() { + directory_overrides.push(arguments); + } + } + } + } + + // Return usagetree. + UsageTree { + path: dir.clone(), + name: dir + .file_stem() + .unwrap_or_else(|| panic!("Could not get filename of path '{}'", dir.display())) + .to_str() + .unwrap() + .to_string(), + items: usages, + sub_trees: sub_dirs + .iter() + .map(|dir| UsageTree::new(dir.clone())) + .collect::>(), + override_commands: directory_overrides, + } + } + + /// Format a file or dir name. + pub fn pretty_name(name: &str) -> String { + name.split('_') + .map(|word| word[0..1].to_uppercase() + &word[1..]) + .collect::>() + .join(" ") + } +} +impl Display for UsageTree { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let spacing = " "; + let item_path: String = format!( + "https://github.com/TheAlgorithms/Rust/blob/master/{}", + self.path.display().to_string().replace('\\', "/") + ); + + // Parse files and dirs separately, then sort by name. + let mut entries: Vec<(&str, String)> = Vec::new(); + for sub_tree in &self.sub_trees { + entries.push(( + &sub_tree.name, + sub_tree + .to_string() + .split('\n') + .map(|line| format!("{spacing}{line}")) + .collect::>() + .join("\n"), + )); + } + for item in &self.items { + entries.push(( + item, + format!( + "{spacing}* [{}]({}/{}.rs)", + Self::pretty_name(item), + item_path, + item + ), + )); + } + entries.sort_by(|a, b| a.0.cmp(b.0)); + + // Apply override commands to modify order or contents. + for command in &self.override_commands { + let err_main: String = format!( + "Error overriding DIRECTORY.md with command '{}': ", + command.join(" ") + ); + + // Parse command basics. + if command.len() < 3 { + panic!("{err_main}too few parameters."); + } + let mut command_target_index: usize = command[1].parse::().unwrap_or( + entries + .iter() + .position(|(name, _)| name == &command[1]) + .unwrap_or_else(|| panic!("{err_main}could not find target '{}'.", command[1])), + ); + if command_target_index > entries.len() { + panic!("{err_main}No element at index {}.", command_target_index); + } + command_target_index += match command[0].as_str() { + "before" => 0, + "at" => 0, + "after" => 1, + _ => panic!("{err_main}first word should always be 'before', 'at' or 'after'."), + }; + + // Execute the command's specifics. + match command[2].as_str() { + // Reposition an element. + "place" => { + if command.len() < 4 { + panic!("{err_main}move command requires 4 arguments."); + } + let source_index: usize = entries + .iter() + .position(|(name, _)| name == &command[3]) + .unwrap_or_else(|| { + panic!("{err_main}could not find target '{}'.", command[3]) + }); + let item = entries.remove(source_index); + entries.insert(command_target_index, item); + } + + // Hide an element. + "hide" => { + entries.remove(command_target_index); + } + + // Insert a new text under the selected element. + "insert" => { + if command.len() < 4 { + panic!("{err_main}insert command requires 4 arguments."); + } + let current_contents: &str = &entries[command_target_index].1; + let padding: &str = ¤t_contents + [..current_contents.len() - current_contents.trim_start().len()]; + entries.insert( + command_target_index, + ("", padding.to_string() + &command[3..].join(" ")), + ); + } + + // Unknown command. + _ => panic!("{err_main}unknown command '{}'.", command[2]), + } + } + + write!( + f, + "* {}\n{}", + Self::pretty_name(&self.name), + entries + .iter() + .map(|entry| entry.1.clone()) + .collect::>() + .join("\n") + ) + } +} diff --git a/src/backtracking/mod.rs b/src/backtracking/mod.rs index d8ffb85f6d0..440bc2d4878 100644 --- a/src/backtracking/mod.rs +++ b/src/backtracking/mod.rs @@ -1,3 +1,4 @@ +/* auto-exports start */ mod all_combination_of_size_k; mod n_queens; mod permutations; @@ -7,3 +8,4 @@ pub use all_combination_of_size_k::generate_all_combinations; pub use n_queens::n_queens_solver; pub use permutations::permute; pub use sudoku::Sudoku; +/* auto-exports end */ diff --git a/src/big_integer/fast_factorial.rs b/src/big_integer/fast_factorial.rs index 567e41f4b47..f90c0f5963a 100644 --- a/src/big_integer/fast_factorial.rs +++ b/src/big_integer/fast_factorial.rs @@ -64,7 +64,7 @@ pub fn fast_factorial(n: usize) -> BigUint { #[cfg(test)] mod tests { use super::*; - use crate::math::factorial::factorial_bigmath; + use crate::math::factorial_bigmath; #[test] fn fact() { diff --git a/src/big_integer/mod.rs b/src/big_integer/mod.rs index 4e20752f1a5..aeb5478f077 100644 --- a/src/big_integer/mod.rs +++ b/src/big_integer/mod.rs @@ -1,7 +1,9 @@ #![cfg(feature = "big-math")] +/* auto-exports start */ mod fast_factorial; mod poly1305; -pub use self::fast_factorial::fast_factorial; -pub use self::poly1305::Poly1305; +pub use fast_factorial::fast_factorial; +pub use poly1305::Poly1305; +/* auto-exports end */ diff --git a/src/bit_manipulation/mod.rs b/src/bit_manipulation/mod.rs index 1c9fae8d3af..58ef90e842a 100644 --- a/src/bit_manipulation/mod.rs +++ b/src/bit_manipulation/mod.rs @@ -1,3 +1,4 @@ +/* auto-exports start */ mod counting_bits; mod highest_set_bit; mod sum_of_two_integers; @@ -5,3 +6,4 @@ mod sum_of_two_integers; pub use counting_bits::count_set_bits; pub use highest_set_bit::find_highest_set_bit; pub use sum_of_two_integers::add_two_integers; +/* auto-exports end */ diff --git a/src/ciphers/mod.rs b/src/ciphers/mod.rs index f7a55b0014d..066c1131b0d 100644 --- a/src/ciphers/mod.rs +++ b/src/ciphers/mod.rs @@ -1,3 +1,4 @@ +/* auto-exports start exclusions=[AesKey, xor_bytes] */ mod aes; mod another_rot13; mod baconian_cipher; @@ -14,32 +15,58 @@ mod rail_fence; mod rot13; mod salsa; mod sha256; -mod sha3; mod tea; mod theoretical_rot13; mod transposition; mod vigenere; mod xor; -pub use self::aes::{aes_decrypt, aes_encrypt, AesKey}; -pub use self::another_rot13::another_rot13; -pub use self::baconian_cipher::{baconian_decode, baconian_encode}; -pub use self::base64::{base64_decode, base64_encode}; -pub use self::blake2b::blake2b; -pub use self::caesar::caesar; -pub use self::chacha::chacha20; -pub use self::diffie_hellman::DiffieHellman; -pub use self::hashing_traits::Hasher; -pub use self::hashing_traits::HMAC; -pub use self::kerninghan::kerninghan; -pub use self::morse_code::{decode, encode}; -pub use self::polybius::{decode_ascii, encode_ascii}; -pub use self::rail_fence::{rail_fence_decrypt, rail_fence_encrypt}; -pub use self::rot13::rot13; -pub use self::salsa::salsa20; -pub use self::sha256::SHA256; -pub use self::sha3::{sha3_224, sha3_256, sha3_384, sha3_512}; -pub use self::tea::{tea_decrypt, tea_encrypt}; -pub use self::theoretical_rot13::theoretical_rot13; -pub use self::transposition::transposition; -pub use self::vigenere::vigenere; -pub use self::xor::xor; + +pub use aes::{ + aes_encrypt, + aes_decrypt +}; +pub use another_rot13::another_rot13; +pub use baconian_cipher::{ + baconian_encode, + baconian_decode +}; +pub use base64::{ + base64_encode, + base64_decode +}; +pub use blake2b::blake2b; +pub use caesar::caesar; +pub use chacha::chacha20; +pub use diffie_hellman::DiffieHellman; +pub use hashing_traits::{ + Hasher, + HMAC +}; +pub use kerninghan::kerninghan; +pub use morse_code::{ + encode, + decode +}; +pub use polybius::{ + encode_ascii, + decode_ascii +}; +pub use rail_fence::{ + rail_fence_encrypt, + rail_fence_decrypt +}; +pub use rot13::rot13; +pub use salsa::salsa20; +pub use sha256::SHA256; +pub use tea::{ + tea_encrypt, + tea_decrypt +}; +pub use theoretical_rot13::theoretical_rot13; +pub use transposition::transposition; +pub use vigenere::vigenere; +pub use xor::xor; +/* auto-exports end */ + +mod sha3; +pub use sha3::{sha3_224, sha3_256, sha3_384, sha3_512}; diff --git a/src/compression/mod.rs b/src/compression/mod.rs index 7759b3ab8e4..73f769c9087 100644 --- a/src/compression/mod.rs +++ b/src/compression/mod.rs @@ -1,3 +1,8 @@ +/* auto-exports start */ mod run_length_encoding; -pub use self::run_length_encoding::{run_length_decode, run_length_encode}; +pub use run_length_encoding::{ + run_length_encode, + run_length_decode +}; +/* auto-exports end */ diff --git a/src/conversions/mod.rs b/src/conversions/mod.rs index af02e16a631..28466fb2ecc 100644 --- a/src/conversions/mod.rs +++ b/src/conversions/mod.rs @@ -1,3 +1,4 @@ +/* auto-exports start */ mod binary_to_decimal; mod binary_to_hexadecimal; mod decimal_to_binary; @@ -6,11 +7,13 @@ mod hexadecimal_to_binary; mod hexadecimal_to_decimal; mod octal_to_binary; mod octal_to_decimal; -pub use self::binary_to_decimal::binary_to_decimal; -pub use self::binary_to_hexadecimal::binary_to_hexadecimal; -pub use self::decimal_to_binary::decimal_to_binary; -pub use self::decimal_to_hexadecimal::decimal_to_hexadecimal; -pub use self::hexadecimal_to_binary::hexadecimal_to_binary; -pub use self::hexadecimal_to_decimal::hexadecimal_to_decimal; -pub use self::octal_to_binary::octal_to_binary; -pub use self::octal_to_decimal::octal_to_decimal; + +pub use binary_to_decimal::binary_to_decimal; +pub use binary_to_hexadecimal::binary_to_hexadecimal; +pub use decimal_to_binary::decimal_to_binary; +pub use decimal_to_hexadecimal::decimal_to_hexadecimal; +pub use hexadecimal_to_binary::hexadecimal_to_binary; +pub use hexadecimal_to_decimal::hexadecimal_to_decimal; +pub use octal_to_binary::octal_to_binary; +pub use octal_to_decimal::octal_to_decimal; +/* auto-exports end */ diff --git a/src/data_structures/mod.rs b/src/data_structures/mod.rs index d02b40e19b7..ffc1922f4df 100644 --- a/src/data_structures/mod.rs +++ b/src/data_structures/mod.rs @@ -1,6 +1,9 @@ +/* auto-exports start exclusions=[Iter, NodeNotInGraph, Graph, Hashable, Node, RBNode, RBTreeIterator, IntoIter, IterMut, VebTreeIter, segment_tree_recursive] */ +pub mod probabilistic; + mod avl_tree; -mod b_tree; mod binary_search_tree; +mod b_tree; mod fenwick_tree; mod floyds_algorithm; mod graph; @@ -10,40 +13,44 @@ mod infix_to_postfix; mod lazy_segment_tree; mod linked_list; mod postfix_evaluation; -mod probabilistic; mod queue; mod range_minimum_query; mod rb_tree; mod segment_tree; -mod segment_tree_recursive; mod stack_using_singly_linked_list; mod treap; mod trie; mod union_find; mod veb_tree; -pub use self::avl_tree::AVLTree; -pub use self::b_tree::BTree; -pub use self::binary_search_tree::BinarySearchTree; -pub use self::fenwick_tree::FenwickTree; -pub use self::floyds_algorithm::{detect_cycle, has_cycle}; -pub use self::graph::DirectedGraph; -pub use self::graph::UndirectedGraph; -pub use self::hash_table::HashTable; -pub use self::heap::Heap; -pub use self::infix_to_postfix::infix_to_postfix; -pub use self::lazy_segment_tree::LazySegmentTree; -pub use self::linked_list::LinkedList; -pub use self::postfix_evaluation::evaluate_postfix; -pub use self::probabilistic::bloom_filter; -pub use self::probabilistic::count_min_sketch; -pub use self::queue::Queue; -pub use self::range_minimum_query::RangeMinimumQuery; -pub use self::rb_tree::RBTree; -pub use self::segment_tree::SegmentTree; -pub use self::segment_tree_recursive::SegmentTree as SegmentTreeRecursive; -pub use self::stack_using_singly_linked_list::Stack; -pub use self::treap::Treap; -pub use self::trie::Trie; -pub use self::union_find::UnionFind; -pub use self::veb_tree::VebTree; +pub use avl_tree::AVLTree; +pub use binary_search_tree::BinarySearchTree; +pub use b_tree::BTree; +pub use fenwick_tree::FenwickTree; +pub use floyds_algorithm::{ + detect_cycle, + has_cycle +}; +pub use graph::{ + DirectedGraph, + UndirectedGraph +}; +pub use hash_table::HashTable; +pub use heap::Heap; +pub use infix_to_postfix::infix_to_postfix; +pub use lazy_segment_tree::LazySegmentTree; +pub use linked_list::LinkedList; +pub use postfix_evaluation::evaluate_postfix; +pub use queue::Queue; +pub use range_minimum_query::RangeMinimumQuery; +pub use rb_tree::RBTree; +pub use segment_tree::SegmentTree; +pub use stack_using_singly_linked_list::Stack; +pub use treap::Treap; +pub use trie::Trie; +pub use union_find::UnionFind; +pub use veb_tree::VebTree; +/* auto-exports end */ + +mod segment_tree_recursive; +pub use segment_tree_recursive::SegmentTree as SegmentTreeRecursive; diff --git a/src/data_structures/probabilistic/mod.rs b/src/data_structures/probabilistic/mod.rs index de55027f15f..be37c06e05d 100644 --- a/src/data_structures/probabilistic/mod.rs +++ b/src/data_structures/probabilistic/mod.rs @@ -1,2 +1,10 @@ -pub mod bloom_filter; -pub mod count_min_sketch; +/* auto-exports start */ +mod bloom_filter; +mod count_min_sketch; + +pub use bloom_filter::MultiBinaryBloomFilter; +pub use count_min_sketch::{ + CountMinSketch, + HashCountMinSketch +}; +/* auto-exports end */ diff --git a/src/dynamic_programming/mod.rs b/src/dynamic_programming/mod.rs index ad97d345855..d44e554cc64 100644 --- a/src/dynamic_programming/mod.rs +++ b/src/dynamic_programming/mod.rs @@ -1,3 +1,4 @@ +/* auto-exports start */ mod coin_change; mod egg_dropping; mod fibonacci; @@ -17,28 +18,31 @@ mod snail; mod subset_generation; mod word_break; -pub use self::coin_change::coin_change; -pub use self::egg_dropping::egg_drop; -pub use self::fibonacci::classical_fibonacci; -pub use self::fibonacci::fibonacci; -pub use self::fibonacci::last_digit_of_the_sum_of_nth_fibonacci_number; -pub use self::fibonacci::logarithmic_fibonacci; -pub use self::fibonacci::matrix_fibonacci; -pub use self::fibonacci::memoized_fibonacci; -pub use self::fibonacci::nth_fibonacci_number_modulo_m; -pub use self::fibonacci::recursive_fibonacci; -pub use self::fractional_knapsack::fractional_knapsack; -pub use self::is_subsequence::is_subsequence; -pub use self::knapsack::knapsack; -pub use self::longest_common_subsequence::longest_common_subsequence; -pub use self::longest_common_substring::longest_common_substring; -pub use self::longest_continuous_increasing_subsequence::longest_continuous_increasing_subsequence; -pub use self::longest_increasing_subsequence::longest_increasing_subsequence; -pub use self::matrix_chain_multiply::matrix_chain_multiply; -pub use self::maximal_square::maximal_square; -pub use self::maximum_subarray::maximum_subarray; -pub use self::minimum_cost_path::minimum_cost_path; -pub use self::rod_cutting::rod_cut; -pub use self::snail::snail; -pub use self::subset_generation::list_subset; -pub use self::word_break::word_break; +pub use coin_change::coin_change; +pub use egg_dropping::egg_drop; +pub use fibonacci::{ + fibonacci, + recursive_fibonacci, + classical_fibonacci, + logarithmic_fibonacci, + memoized_fibonacci, + matrix_fibonacci, + nth_fibonacci_number_modulo_m, + last_digit_of_the_sum_of_nth_fibonacci_number +}; +pub use fractional_knapsack::fractional_knapsack; +pub use is_subsequence::is_subsequence; +pub use knapsack::knapsack; +pub use longest_common_subsequence::longest_common_subsequence; +pub use longest_common_substring::longest_common_substring; +pub use longest_continuous_increasing_subsequence::longest_continuous_increasing_subsequence; +pub use longest_increasing_subsequence::longest_increasing_subsequence; +pub use matrix_chain_multiply::matrix_chain_multiply; +pub use maximal_square::maximal_square; +pub use maximum_subarray::maximum_subarray; +pub use minimum_cost_path::minimum_cost_path; +pub use rod_cutting::rod_cut; +pub use snail::snail; +pub use subset_generation::list_subset; +pub use word_break::word_break; +/* auto-exports end */ diff --git a/src/general/mod.rs b/src/general/mod.rs index 3572b146f4a..b9f99ebb6cd 100644 --- a/src/general/mod.rs +++ b/src/general/mod.rs @@ -1,25 +1,30 @@ +/* auto-exports start exclusions=[Chromosome, SelectionStrategy, RouletteWheel, Tournament, GenericAlgorithmParams, HuffmanValue, HuffmanNode] */ +pub mod permutations; + 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 self::hanoi::hanoi; -pub use self::huffman_encoding::{HuffmanDictionary, HuffmanEncoding}; -pub use self::kadane_algorithm::max_sub_array; -pub use self::kmeans::f32::kmeans as kmeans_f32; -pub use self::kmeans::f64::kmeans as kmeans_f64; -pub use self::mex::mex_using_set; -pub use self::mex::mex_using_sort; -pub use self::permutations::{ - heap_permute, permute, permute_unique, steinhaus_johnson_trotter_permute, +pub use convex_hull::convex_hull_graham; +pub use fisher_yates_shuffle::fisher_yates_shuffle; +pub use genetic::GeneticAlgorithm; +pub use hanoi::hanoi; +pub use huffman_encoding::{ + HuffmanDictionary, + HuffmanEncoding +}; +pub use kadane_algorithm::max_sub_array; +pub use mex::{ + mex_using_set, + mex_using_sort }; -pub use self::two_sum::two_sum; +pub use two_sum::two_sum; +/* auto-exports end */ + +mod kmeans; +pub use kmeans::{f32::kmeans as kmeans_f32, f64::kmeans as kmeans_f64}; diff --git a/src/general/permutations/mod.rs b/src/general/permutations/mod.rs index 3e872a50956..eb0a14d4246 100644 --- a/src/general/permutations/mod.rs +++ b/src/general/permutations/mod.rs @@ -1,10 +1,15 @@ +/* auto-exports start */ 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; +pub use heap::heap_permute; +pub use naive::{ + permute, + permute_unique +}; +pub use steinhaus_johnson_trotter::steinhaus_johnson_trotter_permute; +/* auto-exports end */ #[cfg(test)] mod tests { diff --git a/src/geometry/mod.rs b/src/geometry/mod.rs index 5124b821521..67fd7a4b0e1 100644 --- a/src/geometry/mod.rs +++ b/src/geometry/mod.rs @@ -1,3 +1,4 @@ +/* auto-exports start exclusions=[polygon_area] */ mod closest_points; mod graham_scan; mod jarvis_scan; @@ -5,9 +6,10 @@ mod point; mod polygon_points; 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_points; -pub use self::segment::Segment; +pub use closest_points::closest_points; +pub use graham_scan::graham_scan; +pub use jarvis_scan::jarvis_march; +pub use point::Point; +pub use polygon_points::lattice_points; +pub use segment::Segment; +/* auto-exports end */ diff --git a/src/graph/mod.rs b/src/graph/mod.rs index ba54c8dbefc..b164e77bad9 100644 --- a/src/graph/mod.rs +++ b/src/graph/mod.rs @@ -1,3 +1,4 @@ +/* auto-exports start exclusions=[Node, Edge, Graph, Vertex, Edge, FlowEdge, FlowResultEdge, DSUNode, bfs, LCAQuery, QueryAnswer, TopoligicalSortError] */ mod astar; mod bellman_ford; mod bipartite_matching; @@ -24,28 +25,42 @@ mod tarjans_ssc; mod topological_sort; mod two_satisfiability; -pub use self::astar::astar; -pub use self::bellman_ford::bellman_ford; -pub use self::bipartite_matching::BipartiteMatching; -pub use self::breadth_first_search::breadth_first_search; -pub use self::centroid_decomposition::CentroidDecomposition; -pub use self::depth_first_search::depth_first_search; -pub use self::depth_first_search_tic_tac_toe::minimax; -pub use self::dijkstra::dijkstra; -pub use self::dinic_maxflow::DinicMaxFlow; -pub use self::disjoint_set_union::DisjointSetUnion; -pub use self::eulerian_path::EulerianPath; -pub use self::floyd_warshall::floyd_warshall; -pub use self::ford_fulkerson::ford_fulkerson; -pub use self::graph_enumeration::enumerate_graph; -pub use self::heavy_light_decomposition::HeavyLightDecomposition; -pub use self::kosaraju::kosaraju; -pub use self::lee_breadth_first_search::lee; -pub use self::lowest_common_ancestor::{LowestCommonAncestorOffline, LowestCommonAncestorOnline}; -pub use self::minimum_spanning_tree::kruskal; -pub use self::prim::{prim, prim_with_start}; -pub use self::prufer_code::{prufer_decode, prufer_encode}; -pub use self::strongly_connected_components::StronglyConnectedComponents; -pub use self::tarjans_ssc::tarjan_scc; -pub use self::topological_sort::topological_sort; -pub use self::two_satisfiability::solve_two_satisfiability; +pub use astar::astar; +pub use bellman_ford::bellman_ford; +pub use bipartite_matching::BipartiteMatching; +pub use breadth_first_search::breadth_first_search; +pub use centroid_decomposition::CentroidDecomposition; +pub use depth_first_search::depth_first_search; +pub use depth_first_search_tic_tac_toe::{ + Players, + PlayActions, + minimax +}; +pub use dijkstra::dijkstra; +pub use dinic_maxflow::DinicMaxFlow; +pub use disjoint_set_union::DisjointSetUnion; +pub use eulerian_path::EulerianPath; +pub use floyd_warshall::floyd_warshall; +pub use ford_fulkerson::ford_fulkerson; +pub use graph_enumeration::enumerate_graph; +pub use heavy_light_decomposition::HeavyLightDecomposition; +pub use kosaraju::kosaraju; +pub use lee_breadth_first_search::lee; +pub use lowest_common_ancestor::{ + LowestCommonAncestorOnline, + LowestCommonAncestorOffline +}; +pub use minimum_spanning_tree::kruskal; +pub use prim::{ + prim, + prim_with_start +}; +pub use prufer_code::{ + prufer_encode, + prufer_decode +}; +pub use strongly_connected_components::StronglyConnectedComponents; +pub use tarjans_ssc::tarjan_scc; +pub use topological_sort::topological_sort; +pub use two_satisfiability::solve_two_satisfiability; +/* auto-exports end */ diff --git a/src/lib.rs b/src/lib.rs index 0c92f73c2f3..772c7a27601 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,7 @@ #[macro_use] extern crate lazy_static; + +/* auto-exports start */ pub mod backtracking; pub mod big_integer; pub mod bit_manipulation; @@ -18,6 +20,7 @@ pub mod number_theory; pub mod searching; pub mod sorting; pub mod string; +/* auto-exports end */ #[cfg(test)] mod tests { diff --git a/src/machine_learning/loss_function/mod.rs b/src/machine_learning/loss_function/mod.rs index 45d19b5a946..3827d9839ab 100644 --- a/src/machine_learning/loss_function/mod.rs +++ b/src/machine_learning/loss_function/mod.rs @@ -1,9 +1,11 @@ +/* auto-exports start */ mod hinge_loss; mod kl_divergence_loss; mod mean_absolute_error_loss; mod mean_squared_error_loss; -pub use self::hinge_loss::hng_loss; -pub use self::kl_divergence_loss::kld_loss; -pub use self::mean_absolute_error_loss::mae_loss; -pub use self::mean_squared_error_loss::mse_loss; +pub use hinge_loss::hng_loss; +pub use kl_divergence_loss::kld_loss; +pub use mean_absolute_error_loss::mae_loss; +pub use mean_squared_error_loss::mse_loss; +/* auto-exports end */ diff --git a/src/machine_learning/mod.rs b/src/machine_learning/mod.rs index 8fdc0e57b1a..13e3c202d0f 100644 --- a/src/machine_learning/mod.rs +++ b/src/machine_learning/mod.rs @@ -1,15 +1,12 @@ +/* auto-exports start */ +pub mod loss_function; +pub mod optimization; + mod cholesky; mod k_means; mod linear_regression; -mod loss_function; -mod optimization; -pub use self::cholesky::cholesky; -pub use self::k_means::k_means; -pub use self::linear_regression::linear_regression; -pub use self::loss_function::hng_loss; -pub use self::loss_function::kld_loss; -pub use self::loss_function::mae_loss; -pub use self::loss_function::mse_loss; -pub use self::optimization::gradient_descent; -pub use self::optimization::Adam; +pub use cholesky::cholesky; +pub use k_means::k_means; +pub use linear_regression::linear_regression; +/* auto-exports end */ diff --git a/src/machine_learning/optimization/mod.rs b/src/machine_learning/optimization/mod.rs index 7a962993beb..30e287c52b5 100644 --- a/src/machine_learning/optimization/mod.rs +++ b/src/machine_learning/optimization/mod.rs @@ -1,5 +1,7 @@ +/* auto-exports start */ mod adam; mod gradient_descent; -pub use self::adam::Adam; -pub use self::gradient_descent::gradient_descent; +pub use adam::Adam; +pub use gradient_descent::gradient_descent; +/* auto-exports end */ diff --git a/src/math/mod.rs b/src/math/mod.rs index 0e225808e6a..80dcadfa8c2 100644 --- a/src/math/mod.rs +++ b/src/math/mod.rs @@ -1,3 +1,4 @@ +/* auto-exports start exclusions=[Point, Complex64, PrimeFieldElementsIter, MatrixElement, gcd_extended, iteration, legendre_symbol, IterMut] */ mod abs; mod aliquot_sum; mod amicable_numbers; @@ -21,11 +22,11 @@ mod elliptic_curve; mod euclidean_distance; mod exponential_linear_unit; mod extended_euclidean_algorithm; -pub mod factorial; +mod factorial; mod factors; +mod faster_perfect_numbers; mod fast_fourier_transform; mod fast_power; -mod faster_perfect_numbers; mod field; mod frizzy_number; mod gaussian_elimination; @@ -80,100 +81,158 @@ mod trig_functions; mod vector_cross_product; mod zellers_congruence_algorithm; -pub use self::abs::abs; -pub use self::aliquot_sum::aliquot_sum; -pub use self::amicable_numbers::amicable_pairs_under_n; -pub use self::area_of_polygon::area_of_polygon; -pub use self::area_under_curve::area_under_curve; -pub use self::armstrong_number::is_armstrong_number; -pub use self::average::{mean, median, mode}; -pub use self::baby_step_giant_step::baby_step_giant_step; -pub use self::bell_numbers::bell_number; -pub use self::binary_exponentiation::binary_exponentiation; -pub use self::binomial_coefficient::binom; -pub use self::catalan_numbers::init_catalan; -pub use self::ceil::ceil; -pub use self::chinese_remainder_theorem::chinese_remainder_theorem; -pub use self::collatz_sequence::sequence; -pub use self::combinations::combinations; -pub use self::cross_entropy_loss::cross_entropy_loss; -pub use self::decimal_to_fraction::decimal_to_fraction; -pub use self::doomsday::get_week_day; -pub use self::elliptic_curve::EllipticCurve; -pub use self::euclidean_distance::euclidean_distance; -pub use self::exponential_linear_unit::exponential_linear_unit; -pub use self::extended_euclidean_algorithm::extended_euclidean_algorithm; -pub use self::factorial::{factorial, factorial_bigmath, factorial_recursive}; -pub use self::factors::factors; -pub use self::fast_fourier_transform::{ - fast_fourier_transform, fast_fourier_transform_input_permutation, - inverse_fast_fourier_transform, -}; -pub use self::fast_power::fast_power; -pub use self::faster_perfect_numbers::generate_perfect_numbers; -pub use self::field::{Field, PrimeField}; -pub use self::frizzy_number::get_nth_frizzy; -pub use self::gaussian_elimination::gaussian_elimination; -pub use self::gaussian_error_linear_unit::gaussian_error_linear_unit; -pub use self::gcd_of_n_numbers::gcd; -pub use self::geometric_series::geometric_series; -pub use self::greatest_common_divisor::{ - greatest_common_divisor_iterative, greatest_common_divisor_recursive, - greatest_common_divisor_stein, -}; -pub use self::huber_loss::huber_loss; -pub use self::interest::{compound_interest, simple_interest}; -pub use self::interpolation::{lagrange_polynomial_interpolation, linear_interpolation}; -pub use self::interquartile_range::interquartile_range; -pub use self::karatsuba_multiplication::multiply; -pub use self::lcm_of_n_numbers::lcm; -pub use self::leaky_relu::leaky_relu; -pub use self::least_square_approx::least_square_approx; -pub use self::linear_sieve::LinearSieve; -pub use self::logarithm::log; -pub use self::lucas_series::dynamic_lucas_number; -pub use self::lucas_series::recursive_lucas_number; -pub use self::matrix_ops::Matrix; -pub use self::mersenne_primes::{get_mersenne_primes, is_mersenne_prime}; -pub use self::miller_rabin::{big_miller_rabin, miller_rabin}; -pub use self::modular_exponential::{mod_inverse, modular_exponential}; -pub use self::newton_raphson::find_root; -pub use self::nthprime::nthprime; -pub use self::pascal_triangle::pascal_triangle; -pub use self::perfect_cube::perfect_cube_binary_search; -pub use self::perfect_numbers::perfect_numbers; -pub use self::perfect_square::perfect_square; -pub use self::perfect_square::perfect_square_binary_search; -pub use self::pollard_rho::{pollard_rho_factorize, pollard_rho_get_one_factor}; -pub use self::prime_check::prime_check; -pub use self::prime_factors::prime_factors; -pub use self::prime_numbers::prime_numbers; -pub use self::quadratic_residue::{cipolla, tonelli_shanks}; -pub use self::random::PCG32; -pub use self::relu::relu; -pub use self::sieve_of_eratosthenes::sieve_of_eratosthenes; -pub use self::sigmoid::sigmoid; -pub use self::signum::signum; -pub use self::simpsons_integration::simpsons_integration; -pub use self::softmax::softmax; -pub use self::sprague_grundy_theorem::calculate_grundy_number; -pub use self::square_pyramidal_numbers::square_pyramidal_number; -pub use self::square_root::{fast_inv_sqrt, square_root}; -pub use self::sum_of_digits::{sum_digits_iterative, sum_digits_recursive}; -pub use self::sum_of_geometric_progression::sum_of_geometric_progression; -pub use self::sum_of_harmonic_series::sum_of_harmonic_progression; -pub use self::sylvester_sequence::sylvester; -pub use self::tanh::tanh; -pub use self::trapezoidal_integration::trapezoidal_integral; -pub use self::trial_division::trial_division; -pub use self::trig_functions::cosine; -pub use self::trig_functions::cosine_no_radian_arg; -pub use self::trig_functions::cotan; -pub use self::trig_functions::cotan_no_radian_arg; -pub use self::trig_functions::sine; -pub use self::trig_functions::sine_no_radian_arg; -pub use self::trig_functions::tan; -pub use self::trig_functions::tan_no_radian_arg; -pub use self::vector_cross_product::cross_product; -pub use self::vector_cross_product::vector_magnitude; -pub use self::zellers_congruence_algorithm::zellers_congruence_algorithm; +pub use abs::abs; +pub use aliquot_sum::aliquot_sum; +pub use amicable_numbers::amicable_pairs_under_n; +pub use area_of_polygon::area_of_polygon; +pub use area_under_curve::area_under_curve; +pub use armstrong_number::is_armstrong_number; +pub use average::{ + mean, + median, + mode +}; +pub use baby_step_giant_step::baby_step_giant_step; +pub use bell_numbers::bell_number; +pub use binary_exponentiation::binary_exponentiation; +pub use binomial_coefficient::binom; +pub use catalan_numbers::init_catalan; +pub use ceil::ceil; +pub use chinese_remainder_theorem::chinese_remainder_theorem; +pub use collatz_sequence::sequence; +pub use combinations::combinations; +pub use cross_entropy_loss::cross_entropy_loss; +pub use decimal_to_fraction::decimal_to_fraction; +pub use doomsday::{ + doomsday, + get_week_day +}; +pub use elliptic_curve::EllipticCurve; +pub use euclidean_distance::euclidean_distance; +pub use exponential_linear_unit::exponential_linear_unit; +pub use extended_euclidean_algorithm::extended_euclidean_algorithm; +pub use factorial::{ + factorial, + factorial_recursive, + factorial_bigmath +}; +pub use factors::factors; +pub use faster_perfect_numbers::generate_perfect_numbers; +pub use fast_fourier_transform::{ + fast_fourier_transform_input_permutation, + fast_fourier_transform, + inverse_fast_fourier_transform +}; +pub use fast_power::fast_power; +pub use field::{ + Field, + PrimeField +}; +pub use frizzy_number::get_nth_frizzy; +pub use gaussian_elimination::gaussian_elimination; +pub use gaussian_error_linear_unit::gaussian_error_linear_unit; +pub use gcd_of_n_numbers::gcd; +pub use geometric_series::geometric_series; +pub use greatest_common_divisor::{ + greatest_common_divisor_recursive, + greatest_common_divisor_iterative, + greatest_common_divisor_stein +}; +pub use huber_loss::huber_loss; +pub use interest::{ + simple_interest, + compound_interest +}; +pub use interpolation::{ + linear_interpolation, + lagrange_polynomial_interpolation +}; +pub use interquartile_range::{ + find_median, + interquartile_range +}; +pub use karatsuba_multiplication::multiply; +pub use lcm_of_n_numbers::lcm; +pub use leaky_relu::leaky_relu; +pub use least_square_approx::least_square_approx; +pub use linear_sieve::LinearSieve; +pub use logarithm::log; +pub use lucas_series::{ + recursive_lucas_number, + dynamic_lucas_number +}; +pub use matrix_ops::Matrix; +pub use mersenne_primes::{ + is_mersenne_prime, + get_mersenne_primes +}; +pub use miller_rabin::{ + miller_rabin, + big_miller_rabin +}; +pub use modular_exponential::{ + mod_inverse, + modular_exponential +}; +pub use newton_raphson::find_root; +pub use nthprime::nthprime; +pub use pascal_triangle::pascal_triangle; +pub use perfect_cube::perfect_cube_binary_search; +pub use perfect_numbers::{ + is_perfect_number, + perfect_numbers +}; +pub use perfect_square::{ + perfect_square, + perfect_square_binary_search +}; +pub use pollard_rho::{ + pollard_rho_get_one_factor, + pollard_rho_factorize +}; +pub use prime_check::prime_check; +pub use prime_factors::prime_factors; +pub use prime_numbers::prime_numbers; +pub use quadratic_residue::{ + cipolla, + tonelli_shanks +}; +pub use random::PCG32; +pub use relu::relu; +pub use sieve_of_eratosthenes::sieve_of_eratosthenes; +pub use sigmoid::sigmoid; +pub use signum::signum; +pub use simpsons_integration::simpsons_integration; +pub use softmax::softmax; +pub use sprague_grundy_theorem::calculate_grundy_number; +pub use square_pyramidal_numbers::square_pyramidal_number; +pub use square_root::{ + square_root, + fast_inv_sqrt +}; +pub use sum_of_digits::{ + sum_digits_iterative, + sum_digits_recursive +}; +pub use sum_of_geometric_progression::sum_of_geometric_progression; +pub use sum_of_harmonic_series::sum_of_harmonic_progression; +pub use sylvester_sequence::sylvester; +pub use tanh::tanh; +pub use trapezoidal_integration::trapezoidal_integral; +pub use trial_division::trial_division; +pub use trig_functions::{ + sine, + cosine, + cosine_no_radian_arg, + sine_no_radian_arg, + tan, + cotan, + tan_no_radian_arg, + cotan_no_radian_arg +}; +pub use vector_cross_product::{ + cross_product, + vector_magnitude +}; +pub use zellers_congruence_algorithm::zellers_congruence_algorithm; +/* auto-exports end */ diff --git a/src/navigation/mod.rs b/src/navigation/mod.rs index e62be90acbc..9e3391ced15 100644 --- a/src/navigation/mod.rs +++ b/src/navigation/mod.rs @@ -1,5 +1,7 @@ +/* auto-exports start */ mod bearing; mod haversine; -pub use self::bearing::bearing; -pub use self::haversine::haversine; +pub use bearing::bearing; +pub use haversine::haversine; +/* auto-exports end */ diff --git a/src/number_theory/mod.rs b/src/number_theory/mod.rs index 7d2e0ef14f6..bcd717ca9cf 100644 --- a/src/number_theory/mod.rs +++ b/src/number_theory/mod.rs @@ -1,5 +1,7 @@ +/* auto-exports start */ mod compute_totient; mod kth_factor; -pub use self::compute_totient::compute_totient; -pub use self::kth_factor::kth_factor; +pub use compute_totient::compute_totient; +pub use kth_factor::kth_factor; +/* auto-exports end */ diff --git a/src/searching/mod.rs b/src/searching/mod.rs index 94f65988195..cf0d942f0f9 100644 --- a/src/searching/mod.rs +++ b/src/searching/mod.rs @@ -1,3 +1,4 @@ +/* auto-exports start */ mod binary_search; mod binary_search_recursive; mod exponential_search; @@ -15,21 +16,26 @@ mod ternary_search_min_max; mod ternary_search_min_max_recursive; mod ternary_search_recursive; -pub use self::binary_search::binary_search; -pub use self::binary_search_recursive::binary_search_rec; -pub use self::exponential_search::exponential_search; -pub use self::fibonacci_search::fibonacci_search; -pub use self::interpolation_search::interpolation_search; -pub use self::jump_search::jump_search; -pub use self::kth_smallest::kth_smallest; -pub use self::kth_smallest_heap::kth_smallest_heap; -pub use self::linear_search::linear_search; -pub use self::moore_voting::moore_voting; -pub use self::quick_select::quick_select; -pub use self::saddleback_search::saddleback_search; -pub use self::ternary_search::ternary_search; -pub use self::ternary_search_min_max::ternary_search_max; -pub use self::ternary_search_min_max::ternary_search_min; -pub use self::ternary_search_min_max_recursive::ternary_search_max_rec; -pub use self::ternary_search_min_max_recursive::ternary_search_min_rec; -pub use self::ternary_search_recursive::ternary_search_rec; +pub use binary_search::binary_search; +pub use binary_search_recursive::binary_search_rec; +pub use exponential_search::exponential_search; +pub use fibonacci_search::fibonacci_search; +pub use interpolation_search::interpolation_search; +pub use jump_search::jump_search; +pub use kth_smallest::kth_smallest; +pub use kth_smallest_heap::kth_smallest_heap; +pub use linear_search::linear_search; +pub use moore_voting::moore_voting; +pub use quick_select::quick_select; +pub use saddleback_search::saddleback_search; +pub use ternary_search::ternary_search; +pub use ternary_search_min_max::{ + ternary_search_max, + ternary_search_min +}; +pub use ternary_search_min_max_recursive::{ + ternary_search_max_rec, + ternary_search_min_rec +}; +pub use ternary_search_recursive::ternary_search_rec; +/* auto-exports end */ diff --git a/src/sorting/mod.rs b/src/sorting/mod.rs index 11486f36ab9..a329630e6ba 100644 --- a/src/sorting/mod.rs +++ b/src/sorting/mod.rs @@ -1,3 +1,4 @@ +/* auto-exports start */ mod bead_sort; mod binary_insertion_sort; mod bingo_sort; @@ -26,49 +27,61 @@ mod radix_sort; mod selection_sort; mod shell_sort; mod sleep_sort; -#[cfg(test)] -mod sort_utils; mod stooge_sort; mod tim_sort; mod tree_sort; mod wave_sort; mod wiggle_sort; -pub use self::bead_sort::bead_sort; -pub use self::binary_insertion_sort::binary_insertion_sort; -pub use self::bingo_sort::bingo_sort; -pub use self::bitonic_sort::bitonic_sort; -pub use self::bogo_sort::bogo_sort; -pub use self::bubble_sort::bubble_sort; -pub use self::bucket_sort::bucket_sort; -pub use self::cocktail_shaker_sort::cocktail_shaker_sort; -pub use self::comb_sort::comb_sort; -pub use self::counting_sort::counting_sort; -pub use self::counting_sort::generic_counting_sort; -pub use self::cycle_sort::cycle_sort; -pub use self::dutch_national_flag_sort::dutch_national_flag_sort; -pub use self::exchange_sort::exchange_sort; -pub use self::gnome_sort::gnome_sort; -pub use self::heap_sort::heap_sort; -pub use self::insertion_sort::insertion_sort; -pub use self::intro_sort::intro_sort; -pub use self::merge_sort::bottom_up_merge_sort; -pub use self::merge_sort::top_down_merge_sort; -pub use self::odd_even_sort::odd_even_sort; -pub use self::pancake_sort::pancake_sort; -pub use self::patience_sort::patience_sort; -pub use self::pigeonhole_sort::pigeonhole_sort; -pub use self::quick_sort::{partition, quick_sort}; -pub use self::quick_sort_3_ways::quick_sort_3_ways; -pub use self::radix_sort::radix_sort; -pub use self::selection_sort::selection_sort; -pub use self::shell_sort::shell_sort; -pub use self::sleep_sort::sleep_sort; -pub use self::stooge_sort::stooge_sort; -pub use self::tim_sort::tim_sort; -pub use self::tree_sort::tree_sort; -pub use self::wave_sort::wave_sort; -pub use self::wiggle_sort::wiggle_sort; +pub use bead_sort::bead_sort; +pub use binary_insertion_sort::binary_insertion_sort; +pub use bingo_sort::bingo_sort; +pub use bitonic_sort::bitonic_sort; +pub use bogo_sort::bogo_sort; +pub use bubble_sort::bubble_sort; +pub use bucket_sort::bucket_sort; +pub use cocktail_shaker_sort::cocktail_shaker_sort; +pub use comb_sort::comb_sort; +pub use counting_sort::{ + counting_sort, + generic_counting_sort +}; +pub use cycle_sort::cycle_sort; +pub use dutch_national_flag_sort::{ + Colors, + dutch_national_flag_sort +}; +pub use exchange_sort::exchange_sort; +pub use gnome_sort::gnome_sort; +pub use heap_sort::heap_sort; +pub use insertion_sort::insertion_sort; +pub use intro_sort::intro_sort; +pub use merge_sort::{ + top_down_merge_sort, + bottom_up_merge_sort +}; +pub use odd_even_sort::odd_even_sort; +pub use pancake_sort::pancake_sort; +pub use patience_sort::patience_sort; +pub use pigeonhole_sort::pigeonhole_sort; +pub use quick_sort::{ + partition, + quick_sort +}; +pub use quick_sort_3_ways::quick_sort_3_ways; +pub use radix_sort::radix_sort; +pub use selection_sort::selection_sort; +pub use shell_sort::shell_sort; +pub use sleep_sort::sleep_sort; +pub use stooge_sort::stooge_sort; +pub use tim_sort::tim_sort; +pub use tree_sort::tree_sort; +pub use wave_sort::wave_sort; +pub use wiggle_sort::wiggle_sort; +/* auto-exports end */ + +#[cfg(test)] +mod sort_utils; #[cfg(test)] use std::cmp; diff --git a/src/sorting/sort_utils.rs b/src/sorting/sort_utils.rs index dbabaa7109b..785add32f97 100644 --- a/src/sorting/sort_utils.rs +++ b/src/sorting/sort_utils.rs @@ -2,7 +2,7 @@ use rand::Rng; use std::time::Instant; #[cfg(test)] -pub fn generate_random_vec(n: u32, range_l: i32, range_r: i32) -> Vec { +pub(super) fn generate_random_vec(n: u32, range_l: i32, range_r: i32) -> Vec { let mut arr = Vec::::with_capacity(n as usize); let mut rng = rand::thread_rng(); let mut count = n; @@ -16,7 +16,7 @@ pub fn generate_random_vec(n: u32, range_l: i32, range_r: i32) -> Vec { } #[cfg(test)] -pub fn generate_nearly_ordered_vec(n: u32, swap_times: u32) -> Vec { +pub(super) fn generate_nearly_ordered_vec(n: u32, swap_times: u32) -> Vec { let mut arr: Vec = (0..n as i32).collect(); let mut rng = rand::thread_rng(); @@ -31,26 +31,26 @@ pub fn generate_nearly_ordered_vec(n: u32, swap_times: u32) -> Vec { } #[cfg(test)] -pub fn generate_ordered_vec(n: u32) -> Vec { +pub(super) fn generate_ordered_vec(n: u32) -> Vec { generate_nearly_ordered_vec(n, 0) } #[cfg(test)] -pub fn generate_reverse_ordered_vec(n: u32) -> Vec { +pub(super) fn generate_reverse_ordered_vec(n: u32) -> Vec { let mut arr = generate_ordered_vec(n); arr.reverse(); arr } #[cfg(test)] -pub fn generate_repeated_elements_vec(n: u32, unique_elements: u8) -> Vec { +pub(super) fn generate_repeated_elements_vec(n: u32, unique_elements: u8) -> Vec { let mut rng = rand::thread_rng(); let v = rng.gen_range(0..n as i32); generate_random_vec(n, v, v + unique_elements as i32) } #[cfg(test)] -pub fn log_timed(test_name: &str, f: F) +pub(super) fn log_timed(test_name: &str, f: F) where F: FnOnce(), { diff --git a/src/string/mod.rs b/src/string/mod.rs index cc083935616..883864b3b7f 100644 --- a/src/string/mod.rs +++ b/src/string/mod.rs @@ -1,3 +1,4 @@ +/* auto-exports start */ mod aho_corasick; mod anagram; mod autocomplete_using_trie; @@ -20,28 +21,40 @@ mod suffix_array_manber_myers; mod suffix_tree; mod z_algorithm; -pub use self::aho_corasick::AhoCorasick; -pub use self::anagram::check_anagram; -pub use self::autocomplete_using_trie::Autocomplete; -pub use self::boyer_moore_search::boyer_moore_search; -pub use self::burrows_wheeler_transform::{ - burrows_wheeler_transform, inv_burrows_wheeler_transform, +pub use aho_corasick::AhoCorasick; +pub use anagram::check_anagram; +pub use autocomplete_using_trie::Autocomplete; +pub use boyer_moore_search::boyer_moore_search; +pub use burrows_wheeler_transform::{ + burrows_wheeler_transform, + inv_burrows_wheeler_transform }; -pub use self::duval_algorithm::duval_algorithm; -pub use self::hamming_distance::hamming_distance; -pub use self::jaro_winkler_distance::jaro_winkler_distance; -pub use self::knuth_morris_pratt::knuth_morris_pratt; -pub use self::levenshtein_distance::levenshtein_distance; -pub use self::lipogram::is_lipogram; -pub use self::manacher::manacher; -pub use self::palindrome::is_palindrome; -pub use self::pangram::is_pangram; -pub use self::pangram::PangramStatus; -pub use self::rabin_karp::rabin_karp; -pub use self::reverse::reverse; -pub use self::run_length_encoding::{run_length_decoding, run_length_encoding}; -pub use self::suffix_array::generate_suffix_array; -pub use self::suffix_array_manber_myers::generate_suffix_array_manber_myers; -pub use self::suffix_tree::{Node, SuffixTree}; -pub use self::z_algorithm::match_pattern; -pub use self::z_algorithm::z_array; +pub use duval_algorithm::duval_algorithm; +pub use hamming_distance::hamming_distance; +pub use jaro_winkler_distance::jaro_winkler_distance; +pub use knuth_morris_pratt::knuth_morris_pratt; +pub use levenshtein_distance::levenshtein_distance; +pub use lipogram::is_lipogram; +pub use manacher::manacher; +pub use palindrome::is_palindrome; +pub use pangram::{ + PangramStatus, + is_pangram +}; +pub use rabin_karp::rabin_karp; +pub use reverse::reverse; +pub use run_length_encoding::{ + run_length_encoding, + run_length_decoding +}; +pub use suffix_array::generate_suffix_array; +pub use suffix_array_manber_myers::generate_suffix_array_manber_myers; +pub use suffix_tree::{ + Node, + SuffixTree +}; +pub use z_algorithm::{ + z_array, + match_pattern +}; +/* auto-exports end */