Dataset Viewer
Auto-converted to Parquet Duplicate
function_component
dict
function_name
stringlengths
3
35
focal_code
stringlengths
385
27.9k
file_path
stringlengths
28
76
file_content
stringlengths
869
132k
wrap_class
stringlengths
0
86.6k
class_signature
stringlengths
0
240
struct_class
stringlengths
0
2.87k
package_name
stringclasses
1 value
{ "argument_definitions": [ { "definitions": [ "pub struct Vec<T, #[unstable(feature = \"allocator_api\", issue = \"32838\")] A: Allocator = Global> {\n buf: RawVec<T, A>,\n len: usize,\n}", "pub struct Point {\n pub x: f64,\n pub y: f64,\n}" ], "name": "points", "type": "Vec<Point>" } ], "end_line": 82, "name": "graham_scan", "signature": "pub fn graham_scan(mut points: Vec<Point>) -> Vec<Point>", "start_line": 15 }
graham_scan
pub fn graham_scan(mut points: Vec<Point>) -> Vec<Point> { if points.len() <= 2 { return vec![]; } let min_point = points.iter().min_by(point_min).unwrap().clone(); points.retain(|p| p != &min_point); if points.is_empty() { // edge case where all the points are the same return vec![]; } let point_cmp = |a: &Point, b: &Point| -> Ordering { // Sort points in counter-clockwise direction relative to the min point. We can this by // checking the orientation of consecutive vectors (min_point, a) and (a, b). let orientation = min_point.consecutive_orientation(a, b); if orientation < 0.0 { Ordering::Greater } else if orientation > 0.0 { Ordering::Less } else { let a_dist = min_point.euclidean_distance(a); let b_dist = min_point.euclidean_distance(b); // When two points have the same relative angle to the min point, we should only // include the further point in the convex hull. We sort further points into a lower // index, and in the algorithm, remove all consecutive points with the same relative // angle. b_dist.partial_cmp(&a_dist).unwrap() } }; points.sort_by(point_cmp); let mut convex_hull: Vec<Point> = vec![]; // We always add the min_point, and the first two points in the sorted vec. convex_hull.push(min_point.clone()); convex_hull.push(points[0].clone()); let mut top = 1; for point in points.iter().skip(1) { if min_point.consecutive_orientation(point, &convex_hull[top]) == 0.0 { // Remove consecutive points with the same angle. We make sure include the furthest // point in the convex hull in the sort comparator. continue; } loop { // In this loop, we remove points that we determine are no longer part of the convex // hull. if top <= 1 { break; } // If there is a segment(i+1, i+2) turns right relative to segment(i, i+1), point(i+1) // is not part of the convex hull. let orientation = convex_hull[top - 1].consecutive_orientation(&convex_hull[top], point); if orientation <= 0.0 { top -= 1; convex_hull.pop(); } else { break; } } convex_hull.push(point.clone()); top += 1; } if convex_hull.len() <= 2 { return vec![]; } convex_hull }
Rust-master/src/geometry/graham_scan.rs
use crate::geometry::Point; use std::cmp::Ordering; fn point_min(a: &&Point, b: &&Point) -> Ordering { // Find the bottom-most point. In the case of a tie, find the left-most. if a.y == b.y { a.x.partial_cmp(&b.x).unwrap() } else { a.y.partial_cmp(&b.y).unwrap() } } // Returns a Vec of Points that make up the convex hull of `points`. Returns an empty Vec if there // is no convex hull. pub fn graham_scan(mut points: Vec<Point>) -> Vec<Point> { if points.len() <= 2 { return vec![]; } let min_point = points.iter().min_by(point_min).unwrap().clone(); points.retain(|p| p != &min_point); if points.is_empty() { // edge case where all the points are the same return vec![]; } let point_cmp = |a: &Point, b: &Point| -> Ordering { // Sort points in counter-clockwise direction relative to the min point. We can this by // checking the orientation of consecutive vectors (min_point, a) and (a, b). let orientation = min_point.consecutive_orientation(a, b); if orientation < 0.0 { Ordering::Greater } else if orientation > 0.0 { Ordering::Less } else { let a_dist = min_point.euclidean_distance(a); let b_dist = min_point.euclidean_distance(b); // When two points have the same relative angle to the min point, we should only // include the further point in the convex hull. We sort further points into a lower // index, and in the algorithm, remove all consecutive points with the same relative // angle. b_dist.partial_cmp(&a_dist).unwrap() } }; points.sort_by(point_cmp); let mut convex_hull: Vec<Point> = vec![]; // We always add the min_point, and the first two points in the sorted vec. convex_hull.push(min_point.clone()); convex_hull.push(points[0].clone()); let mut top = 1; for point in points.iter().skip(1) { if min_point.consecutive_orientation(point, &convex_hull[top]) == 0.0 { // Remove consecutive points with the same angle. We make sure include the furthest // point in the convex hull in the sort comparator. continue; } loop { // In this loop, we remove points that we determine are no longer part of the convex // hull. if top <= 1 { break; } // If there is a segment(i+1, i+2) turns right relative to segment(i, i+1), point(i+1) // is not part of the convex hull. let orientation = convex_hull[top - 1].consecutive_orientation(&convex_hull[top], point); if orientation <= 0.0 { top -= 1; convex_hull.pop(); } else { break; } } convex_hull.push(point.clone()); top += 1; } if convex_hull.len() <= 2 { return vec![]; } convex_hull } #[cfg(test)] mod tests { use super::graham_scan; use super::Point; fn test_graham(convex_hull: Vec<Point>, others: Vec<Point>) { let mut points = convex_hull.clone(); points.append(&mut others.clone()); let graham = graham_scan(points); for point in convex_hull { assert!(graham.contains(&point)); } for point in others { assert!(!graham.contains(&point)); } } #[test] fn too_few_points() { test_graham(vec![], vec![]); test_graham(vec![], vec![Point::new(0.0, 0.0)]); } #[test] fn duplicate_point() { let p = Point::new(0.0, 0.0); test_graham(vec![], vec![p.clone(), p.clone(), p.clone(), p.clone(), p]); } #[test] fn points_same_line() { let p1 = Point::new(1.0, 0.0); let p2 = Point::new(2.0, 0.0); let p3 = Point::new(3.0, 0.0); let p4 = Point::new(4.0, 0.0); let p5 = Point::new(5.0, 0.0); // let p6 = Point::new(1.0, 1.0); test_graham(vec![], vec![p1, p2, p3, p4, p5]); } #[test] fn triangle() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(1.5, 2.0); let points = vec![p1, p2, p3]; test_graham(points, vec![]); } #[test] fn rectangle() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(2.0, 2.0); let p4 = Point::new(1.0, 2.0); let points = vec![p1, p2, p3, p4]; test_graham(points, vec![]); } #[test] fn triangle_with_points_in_middle() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(1.5, 2.0); let p4 = Point::new(1.5, 1.5); let p5 = Point::new(1.2, 1.3); let p6 = Point::new(1.8, 1.2); let p7 = Point::new(1.5, 1.9); let hull = vec![p1, p2, p3]; let others = vec![p4, p5, p6, p7]; test_graham(hull, others); } #[test] fn rectangle_with_points_in_middle() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(2.0, 2.0); let p4 = Point::new(1.0, 2.0); let p5 = Point::new(1.5, 1.5); let p6 = Point::new(1.2, 1.3); let p7 = Point::new(1.8, 1.2); let p8 = Point::new(1.9, 1.7); let p9 = Point::new(1.4, 1.9); let hull = vec![p1, p2, p3, p4]; let others = vec![p5, p6, p7, p8, p9]; test_graham(hull, others); } #[test] fn star() { // A single stroke star shape (kind of). Only the tips(p1-5) are part of the convex hull. The // other points would create angles >180 degrees if they were part of the polygon. let p1 = Point::new(-5.0, 6.0); let p2 = Point::new(-11.0, 0.0); let p3 = Point::new(-9.0, -8.0); let p4 = Point::new(4.0, 4.0); let p5 = Point::new(6.0, -7.0); let p6 = Point::new(-7.0, -2.0); let p7 = Point::new(-2.0, -4.0); let p8 = Point::new(0.0, 1.0); let p9 = Point::new(1.0, 0.0); let p10 = Point::new(-6.0, 1.0); let hull = vec![p1, p2, p3, p4, p5]; let others = vec![p6, p7, p8, p9, p10]; test_graham(hull, others); } #[test] fn rectangle_with_points_on_same_line() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(2.0, 2.0); let p4 = Point::new(1.0, 2.0); let p5 = Point::new(1.5, 1.0); let p6 = Point::new(1.0, 1.5); let p7 = Point::new(2.0, 1.5); let p8 = Point::new(1.5, 2.0); let hull = vec![p1, p2, p3, p4]; let others = vec![p5, p6, p7, p8]; test_graham(hull, others); } }
{ "argument_definitions": [ { "definitions": [ "pub struct Point {\n pub x: f64,\n pub y: f64,\n}" ], "name": "points", "type": "&[Point]" } ], "end_line": 27, "name": "ramer_douglas_peucker", "signature": "pub fn ramer_douglas_peucker(points: &[Point], epsilon: f64) -> Vec<Point>", "start_line": 3 }
ramer_douglas_peucker
pub fn ramer_douglas_peucker(points: &[Point], epsilon: f64) -> Vec<Point> { if points.len() < 3 { return points.to_vec(); } let mut dmax = 0.0; let mut index = 0; let end = points.len() - 1; for i in 1..end { let d = perpendicular_distance(&points[i], &points[0], &points[end]); if d > dmax { index = i; dmax = d; } } if dmax > epsilon { let mut results = ramer_douglas_peucker(&points[..=index], epsilon); results.pop(); results.extend(ramer_douglas_peucker(&points[index..], epsilon)); results } else { vec![points[0].clone(), points[end].clone()] } }
Rust-master/src/geometry/ramer_douglas_peucker.rs
use crate::geometry::Point; pub fn ramer_douglas_peucker(points: &[Point], epsilon: f64) -> Vec<Point> { if points.len() < 3 { return points.to_vec(); } let mut dmax = 0.0; let mut index = 0; let end = points.len() - 1; for i in 1..end { let d = perpendicular_distance(&points[i], &points[0], &points[end]); if d > dmax { index = i; dmax = d; } } if dmax > epsilon { let mut results = ramer_douglas_peucker(&points[..=index], epsilon); results.pop(); results.extend(ramer_douglas_peucker(&points[index..], epsilon)); results } else { vec![points[0].clone(), points[end].clone()] } } fn perpendicular_distance(p: &Point, a: &Point, b: &Point) -> f64 { let num = (b.y - a.y) * p.x - (b.x - a.x) * p.y + b.x * a.y - b.y * a.x; let den = a.euclidean_distance(b); num.abs() / den } #[cfg(test)] mod tests { use super::*; macro_rules! test_perpendicular_distance { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (p, a, b, expected) = $test_case; assert_eq!(perpendicular_distance(&p, &a, &b), expected); assert_eq!(perpendicular_distance(&p, &b, &a), expected); } )* }; } test_perpendicular_distance! { basic: (Point::new(4.0, 0.0), Point::new(0.0, 0.0), Point::new(0.0, 3.0), 4.0), basic_shifted_1: (Point::new(4.0, 1.0), Point::new(0.0, 1.0), Point::new(0.0, 4.0), 4.0), basic_shifted_2: (Point::new(2.0, 1.0), Point::new(-2.0, 1.0), Point::new(-2.0, 4.0), 4.0), } #[test] fn test_ramer_douglas_peucker_polygon() { let a = Point::new(0.0, 0.0); let b = Point::new(1.0, 0.0); let c = Point::new(2.0, 0.0); let d = Point::new(2.0, 1.0); let e = Point::new(2.0, 2.0); let f = Point::new(1.0, 2.0); let g = Point::new(0.0, 2.0); let h = Point::new(0.0, 1.0); let polygon = vec![ a.clone(), b, c.clone(), d, e.clone(), f, g.clone(), h.clone(), ]; let epsilon = 0.7; let result = ramer_douglas_peucker(&polygon, epsilon); assert_eq!(result, vec![a, c, e, g, h]); } #[test] fn test_ramer_douglas_peucker_polygonal_chain() { let a = Point::new(0., 0.); let b = Point::new(2., 0.5); let c = Point::new(3., 3.); let d = Point::new(6., 3.); let e = Point::new(8., 4.); let points = vec![a.clone(), b, c, d, e.clone()]; let epsilon = 3.; // The epsilon is quite large, so the result will be a single line let result = ramer_douglas_peucker(&points, epsilon); assert_eq!(result, vec![a, e]); } #[test] fn test_less_than_three_points() { let a = Point::new(0., 0.); let b = Point::new(1., 1.); let epsilon = 0.1; assert_eq!(ramer_douglas_peucker(&[], epsilon), vec![]); assert_eq!( ramer_douglas_peucker(&[a.clone()], epsilon), vec![a.clone()] ); assert_eq!( ramer_douglas_peucker(&[a.clone(), b.clone()], epsilon), vec![a, b] ); } }
{ "argument_definitions": [ { "definitions": [ "pub struct Vec<T, #[unstable(feature = \"allocator_api\", issue = \"32838\")] A: Allocator = Global> {\n buf: RawVec<T, A>,\n len: usize,\n}" ], "name": "data_points", "type": "Vec<(f64, f64" } ], "end_line": 70, "name": "k_means", "signature": "pub fn k_means(data_points: Vec<(f64, f64)>, n_clusters: usize, max_iter: i32) -> Option<Vec<u32>>", "start_line": 25 }
k_means
pub fn k_means(data_points: Vec<(f64, f64)>, n_clusters: usize, max_iter: i32) -> Option<Vec<u32>> { if data_points.len() < n_clusters { return None; } let mut centroids: Vec<(f64, f64)> = Vec::new(); let mut labels: Vec<u32> = vec![0; data_points.len()]; for _ in 0..n_clusters { let x: f64 = random::<f64>(); let y: f64 = random::<f64>(); centroids.push((x, y)); } let mut count_iter: i32 = 0; while count_iter < max_iter { let mut new_centroids_position: Vec<(f64, f64)> = vec![(0.0, 0.0); n_clusters]; let mut new_centroids_num: Vec<u32> = vec![0; n_clusters]; for (i, d) in data_points.iter().enumerate() { let nearest_cluster = find_nearest(d, &centroids); labels[i] = nearest_cluster; new_centroids_position[nearest_cluster as usize].0 += d.0; new_centroids_position[nearest_cluster as usize].1 += d.1; new_centroids_num[nearest_cluster as usize] += 1; } for i in 0..centroids.len() { if new_centroids_num[i] == 0 { continue; } let new_x: f64 = new_centroids_position[i].0 / new_centroids_num[i] as f64; let new_y: f64 = new_centroids_position[i].1 / new_centroids_num[i] as f64; centroids[i] = (new_x, new_y); } count_iter += 1; } Some(labels) }
Rust-master/src/machine_learning/k_means.rs
use rand::random; fn get_distance(p1: &(f64, f64), p2: &(f64, f64)) -> f64 { let dx: f64 = p1.0 - p2.0; let dy: f64 = p1.1 - p2.1; ((dx * dx) + (dy * dy)).sqrt() } fn find_nearest(data_point: &(f64, f64), centroids: &[(f64, f64)]) -> u32 { let mut cluster: u32 = 0; for (i, c) in centroids.iter().enumerate() { let d1 = get_distance(data_point, c); let d2 = get_distance(data_point, &centroids[cluster as usize]); if d1 < d2 { cluster = i as u32; } } cluster } pub fn k_means(data_points: Vec<(f64, f64)>, n_clusters: usize, max_iter: i32) -> Option<Vec<u32>> { if data_points.len() < n_clusters { return None; } let mut centroids: Vec<(f64, f64)> = Vec::new(); let mut labels: Vec<u32> = vec![0; data_points.len()]; for _ in 0..n_clusters { let x: f64 = random::<f64>(); let y: f64 = random::<f64>(); centroids.push((x, y)); } let mut count_iter: i32 = 0; while count_iter < max_iter { let mut new_centroids_position: Vec<(f64, f64)> = vec![(0.0, 0.0); n_clusters]; let mut new_centroids_num: Vec<u32> = vec![0; n_clusters]; for (i, d) in data_points.iter().enumerate() { let nearest_cluster = find_nearest(d, &centroids); labels[i] = nearest_cluster; new_centroids_position[nearest_cluster as usize].0 += d.0; new_centroids_position[nearest_cluster as usize].1 += d.1; new_centroids_num[nearest_cluster as usize] += 1; } for i in 0..centroids.len() { if new_centroids_num[i] == 0 { continue; } let new_x: f64 = new_centroids_position[i].0 / new_centroids_num[i] as f64; let new_y: f64 = new_centroids_position[i].1 / new_centroids_num[i] as f64; centroids[i] = (new_x, new_y); } count_iter += 1; } Some(labels) } #[cfg(test)] mod test { use super::*; #[test] fn test_k_means() { let mut data_points: Vec<(f64, f64)> = vec![]; let n_points: usize = 1000; for _ in 0..n_points { let x: f64 = random::<f64>() * 100.0; let y: f64 = random::<f64>() * 100.0; data_points.push((x, y)); } println!("{:?}", k_means(data_points, 10, 100).unwrap_or_default()); } }
{ "argument_definitions": [ { "definitions": [ "pub struct Vec<T, #[unstable(feature = \"allocator_api\", issue = \"32838\")] A: Allocator = Global> {\n buf: RawVec<T, A>,\n len: usize,\n}" ], "name": "mat", "type": "Vec<f64>" } ], "end_line": 31, "name": "cholesky", "signature": "pub fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64>", "start_line": 1 }
cholesky
pub fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> { if (mat.is_empty()) || (n == 0) { return vec![]; } let mut res = vec![0.0; mat.len()]; for i in 0..n { for j in 0..=i { let mut s = 0.0; for k in 0..j { s += res[i * n + k] * res[j * n + k]; } let value = if i == j { let diag_value = mat[i * n + i] - s; if diag_value.is_nan() { 0.0 } else { diag_value.sqrt() } } else { let off_diag_value = 1.0 / res[j * n + j] * (mat[i * n + j] - s); if off_diag_value.is_nan() { 0.0 } else { off_diag_value } }; res[i * n + j] = value; } } res }
Rust-master/src/machine_learning/cholesky.rs
pub fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> { if (mat.is_empty()) || (n == 0) { return vec![]; } let mut res = vec![0.0; mat.len()]; for i in 0..n { for j in 0..=i { let mut s = 0.0; for k in 0..j { s += res[i * n + k] * res[j * n + k]; } let value = if i == j { let diag_value = mat[i * n + i] - s; if diag_value.is_nan() { 0.0 } else { diag_value.sqrt() } } else { let off_diag_value = 1.0 / res[j * n + j] * (mat[i * n + j] - s); if off_diag_value.is_nan() { 0.0 } else { off_diag_value } }; res[i * n + j] = value; } } res } #[cfg(test)] mod tests { use super::*; #[test] fn test_cholesky() { // Test case 1 let mat1 = vec![25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0]; let res1 = cholesky(mat1, 3); // The expected Cholesky decomposition values #[allow(clippy::useless_vec)] let expected1 = vec![5.0, 0.0, 0.0, 3.0, 3.0, 0.0, -1.0, 1.0, 3.0]; assert!(res1 .iter() .zip(expected1.iter()) .all(|(a, b)| (a - b).abs() < 1e-6)); } fn transpose_matrix(mat: &[f64], n: usize) -> Vec<f64> { (0..n) .flat_map(|i| (0..n).map(move |j| mat[j * n + i])) .collect() } fn matrix_multiply(mat1: &[f64], mat2: &[f64], n: usize) -> Vec<f64> { (0..n) .flat_map(|i| { (0..n).map(move |j| { (0..n).fold(0.0, |acc, k| acc + mat1[i * n + k] * mat2[k * n + j]) }) }) .collect() } #[test] fn test_matrix_operations() { // Test case 1: Transposition let mat1 = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]; let transposed_mat1 = transpose_matrix(&mat1, 3); let expected_transposed_mat1 = vec![1.0, 4.0, 7.0, 2.0, 5.0, 8.0, 3.0, 6.0, 9.0]; assert_eq!(transposed_mat1, expected_transposed_mat1); // Test case 2: Matrix multiplication let mat2 = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]; let mat3 = vec![9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0]; let multiplied_mat = matrix_multiply(&mat2, &mat3, 3); let expected_multiplied_mat = vec![30.0, 24.0, 18.0, 84.0, 69.0, 54.0, 138.0, 114.0, 90.0]; assert_eq!(multiplied_mat, expected_multiplied_mat); } #[test] fn empty_matrix() { let mat = vec![]; let res = cholesky(mat, 0); assert_eq!(res, vec![]); } #[test] fn matrix_with_all_zeros() { let mat3 = vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; let res3 = cholesky(mat3, 3); let expected3 = vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; assert_eq!(res3, expected3); } }
{ "argument_definitions": [ { "definitions": [ "pub struct Vec<T, #[unstable(feature = \"allocator_api\", issue = \"32838\")] A: Allocator = Global> {\n buf: RawVec<T, A>,\n len: usize,\n}", "pub struct Item {\n weight: usize,\n value: usize,\n}" ], "name": "items", "type": "Vec<Item>" } ], "end_line": 64, "name": "knapsack", "signature": "pub fn knapsack(capacity: usize, items: Vec<Item>) -> KnapsackSolution", "start_line": 45 }
knapsack
pub fn knapsack(capacity: usize, items: Vec<Item>) -> KnapsackSolution { let num_items = items.len(); let item_weights: Vec<usize> = items.iter().map(|item| item.weight).collect(); let item_values: Vec<usize> = items.iter().map(|item| item.value).collect(); let knapsack_matrix = generate_knapsack_matrix(capacity, &item_weights, &item_values); let items_included = retrieve_knapsack_items(&item_weights, &knapsack_matrix, num_items, capacity); let total_weight = items_included .iter() .map(|&index| item_weights[index - 1]) .sum(); KnapsackSolution { optimal_profit: knapsack_matrix[num_items][capacity], total_weight, item_indices: items_included, } }
Rust-master/src/dynamic_programming/knapsack.rs
//! This module provides functionality to solve the knapsack problem using dynamic programming. //! It includes structures for items and solutions, and functions to compute the optimal solution. use std::cmp::Ordering; /// Represents an item with a weight and a value. #[derive(Debug, PartialEq, Eq)] pub struct Item { weight: usize, value: usize, } /// Represents the solution to the knapsack problem. #[derive(Debug, PartialEq, Eq)] pub struct KnapsackSolution { /// The optimal profit obtained. optimal_profit: usize, /// The total weight of items included in the solution. total_weight: usize, /// The indices of items included in the solution. Indices might not be unique. item_indices: Vec<usize>, } /// Solves the knapsack problem and returns the optimal profit, total weight, and indices of items included. /// /// # Arguments: /// * `capacity` - The maximum weight capacity of the knapsack. /// * `items` - A vector of `Item` structs, each representing an item with weight and value. /// /// # Returns: /// A `KnapsackSolution` struct containing: /// - `optimal_profit` - The maximum profit achievable with the given capacity and items. /// - `total_weight` - The total weight of items included in the solution. /// - `item_indices` - Indices of items included in the solution. Indices might not be unique. /// /// # Note: /// The indices of items in the solution might not be unique. /// This function assumes that `items` is non-empty. /// /// # Complexity: /// - Time complexity: O(num_items * capacity) /// - Space complexity: O(num_items * capacity) /// /// where `num_items` is the number of items and `capacity` is the knapsack capacity. pub fn knapsack(capacity: usize, items: Vec<Item>) -> KnapsackSolution { let num_items = items.len(); let item_weights: Vec<usize> = items.iter().map(|item| item.weight).collect(); let item_values: Vec<usize> = items.iter().map(|item| item.value).collect(); let knapsack_matrix = generate_knapsack_matrix(capacity, &item_weights, &item_values); let items_included = retrieve_knapsack_items(&item_weights, &knapsack_matrix, num_items, capacity); let total_weight = items_included .iter() .map(|&index| item_weights[index - 1]) .sum(); KnapsackSolution { optimal_profit: knapsack_matrix[num_items][capacity], total_weight, item_indices: items_included, } } /// Generates the knapsack matrix (`num_items`, `capacity`) with maximum values. /// /// # Arguments: /// * `capacity` - knapsack capacity /// * `item_weights` - weights of each item /// * `item_values` - values of each item fn generate_knapsack_matrix( capacity: usize, item_weights: &[usize], item_values: &[usize], ) -> Vec<Vec<usize>> { let num_items = item_weights.len(); (0..=num_items).fold( vec![vec![0; capacity + 1]; num_items + 1], |mut matrix, item_index| { (0..=capacity).for_each(|current_capacity| { matrix[item_index][current_capacity] = if item_index == 0 || current_capacity == 0 { 0 } else if item_weights[item_index - 1] <= current_capacity { usize::max( item_values[item_index - 1] + matrix[item_index - 1] [current_capacity - item_weights[item_index - 1]], matrix[item_index - 1][current_capacity], ) } else { matrix[item_index - 1][current_capacity] }; }); matrix }, ) } /// Retrieves the indices of items included in the optimal knapsack solution. /// /// # Arguments: /// * `item_weights` - weights of each item /// * `knapsack_matrix` - knapsack matrix with maximum values /// * `item_index` - number of items to consider (initially the total number of items) /// * `remaining_capacity` - remaining capacity of the knapsack /// /// # Returns /// A vector of item indices included in the optimal solution. The indices might not be unique. fn retrieve_knapsack_items( item_weights: &[usize], knapsack_matrix: &[Vec<usize>], item_index: usize, remaining_capacity: usize, ) -> Vec<usize> { match item_index { 0 => vec![], _ => { let current_value = knapsack_matrix[item_index][remaining_capacity]; let previous_value = knapsack_matrix[item_index - 1][remaining_capacity]; match current_value.cmp(&previous_value) { Ordering::Greater => { let mut knap = retrieve_knapsack_items( item_weights, knapsack_matrix, item_index - 1, remaining_capacity - item_weights[item_index - 1], ); knap.push(item_index); knap } Ordering::Equal | Ordering::Less => retrieve_knapsack_items( item_weights, knapsack_matrix, item_index - 1, remaining_capacity, ), } } } } #[cfg(test)] mod tests { use super::*; macro_rules! knapsack_tests { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (capacity, items, expected) = $test_case; assert_eq!(expected, knapsack(capacity, items)); } )* } } knapsack_tests! { test_basic_knapsack_small: ( 165, vec![ Item { weight: 23, value: 92 }, Item { weight: 31, value: 57 }, Item { weight: 29, value: 49 }, Item { weight: 44, value: 68 }, Item { weight: 53, value: 60 }, Item { weight: 38, value: 43 }, Item { weight: 63, value: 67 }, Item { weight: 85, value: 84 }, Item { weight: 89, value: 87 }, Item { weight: 82, value: 72 } ], KnapsackSolution { optimal_profit: 309, total_weight: 165, item_indices: vec![1, 2, 3, 4, 6] } ), test_basic_knapsack_tiny: ( 26, vec![ Item { weight: 12, value: 24 }, Item { weight: 7, value: 13 }, Item { weight: 11, value: 23 }, Item { weight: 8, value: 15 }, Item { weight: 9, value: 16 } ], KnapsackSolution { optimal_profit: 51, total_weight: 26, item_indices: vec![2, 3, 4] } ), test_basic_knapsack_medium: ( 190, vec![ Item { weight: 56, value: 50 }, Item { weight: 59, value: 50 }, Item { weight: 80, value: 64 }, Item { weight: 64, value: 46 }, Item { weight: 75, value: 50 }, Item { weight: 17, value: 5 } ], KnapsackSolution { optimal_profit: 150, total_weight: 190, item_indices: vec![1, 2, 5] } ), test_diverse_weights_values_small: ( 50, vec![ Item { weight: 31, value: 70 }, Item { weight: 10, value: 20 }, Item { weight: 20, value: 39 }, Item { weight: 19, value: 37 }, Item { weight: 4, value: 7 }, Item { weight: 3, value: 5 }, Item { weight: 6, value: 10 } ], KnapsackSolution { optimal_profit: 107, total_weight: 50, item_indices: vec![1, 4] } ), test_diverse_weights_values_medium: ( 104, vec![ Item { weight: 25, value: 350 }, Item { weight: 35, value: 400 }, Item { weight: 45, value: 450 }, Item { weight: 5, value: 20 }, Item { weight: 25, value: 70 }, Item { weight: 3, value: 8 }, Item { weight: 2, value: 5 }, Item { weight: 2, value: 5 } ], KnapsackSolution { optimal_profit: 900, total_weight: 104, item_indices: vec![1, 3, 4, 5, 7, 8] } ), test_high_value_items: ( 170, vec![ Item { weight: 41, value: 442 }, Item { weight: 50, value: 525 }, Item { weight: 49, value: 511 }, Item { weight: 59, value: 593 }, Item { weight: 55, value: 546 }, Item { weight: 57, value: 564 }, Item { weight: 60, value: 617 } ], KnapsackSolution { optimal_profit: 1735, total_weight: 169, item_indices: vec![2, 4, 7] } ), test_large_knapsack: ( 750, vec![ Item { weight: 70, value: 135 }, Item { weight: 73, value: 139 }, Item { weight: 77, value: 149 }, Item { weight: 80, value: 150 }, Item { weight: 82, value: 156 }, Item { weight: 87, value: 163 }, Item { weight: 90, value: 173 }, Item { weight: 94, value: 184 }, Item { weight: 98, value: 192 }, Item { weight: 106, value: 201 }, Item { weight: 110, value: 210 }, Item { weight: 113, value: 214 }, Item { weight: 115, value: 221 }, Item { weight: 118, value: 229 }, Item { weight: 120, value: 240 } ], KnapsackSolution { optimal_profit: 1458, total_weight: 749, item_indices: vec![1, 3, 5, 7, 8, 9, 14, 15] } ), test_zero_capacity: ( 0, vec![ Item { weight: 1, value: 1 }, Item { weight: 2, value: 2 }, Item { weight: 3, value: 3 } ], KnapsackSolution { optimal_profit: 0, total_weight: 0, item_indices: vec![] } ), test_very_small_capacity: ( 1, vec![ Item { weight: 10, value: 1 }, Item { weight: 20, value: 2 }, Item { weight: 30, value: 3 } ], KnapsackSolution { optimal_profit: 0, total_weight: 0, item_indices: vec![] } ), test_no_items: ( 1, vec![], KnapsackSolution { optimal_profit: 0, total_weight: 0, item_indices: vec![] } ), test_item_too_heavy: ( 1, vec![ Item { weight: 2, value: 100 } ], KnapsackSolution { optimal_profit: 0, total_weight: 0, item_indices: vec![] } ), test_greedy_algorithm_does_not_work: ( 10, vec![ Item { weight: 10, value: 15 }, Item { weight: 6, value: 7 }, Item { weight: 4, value: 9 } ], KnapsackSolution { optimal_profit: 16, total_weight: 10, item_indices: vec![2, 3] } ), test_greedy_algorithm_does_not_work_weight_smaller_than_capacity: ( 10, vec![ Item { weight: 10, value: 15 }, Item { weight: 1, value: 9 }, Item { weight: 2, value: 7 } ], KnapsackSolution { optimal_profit: 16, total_weight: 3, item_indices: vec![2, 3] } ), } }
{ "argument_definitions": [ { "definitions": [ "pub struct Vec<T, #[unstable(feature = \"allocator_api\", issue = \"32838\")] A: Allocator = Global> {\n buf: RawVec<T, A>,\n len: usize,\n}", "pub struct Vec<T, #[unstable(feature = \"allocator_api\", issue = \"32838\")] A: Allocator = Global> {\n buf: RawVec<T, A>,\n len: usize,\n}" ], "name": "matrix", "type": "Vec<Vec<usize>>" } ], "end_line": 65, "name": "minimum_cost_path", "signature": "pub fn minimum_cost_path(matrix: Vec<Vec<usize>>) -> Result<usize, MatrixError>", "start_line": 32 }
minimum_cost_path
pub fn minimum_cost_path(matrix: Vec<Vec<usize>>) -> Result<usize, MatrixError> { // Check if the matrix is rectangular if !matrix.iter().all(|row| row.len() == matrix[0].len()) { return Err(MatrixError::NonRectangularMatrix); } // Check if the matrix is empty or contains empty rows if matrix.is_empty() || matrix.iter().all(|row| row.is_empty()) { return Err(MatrixError::EmptyMatrix); } // Initialize the first row of the cost vector let mut cost = matrix[0] .iter() .scan(0, |acc, &val| { *acc += val; Some(*acc) }) .collect::<Vec<_>>(); // Process each row from the second to the last for row in matrix.iter().skip(1) { // Update the first element of cost for this row cost[0] += row[0]; // Update the rest of the elements in the current row of cost for col in 1..matrix[0].len() { cost[col] = row[col] + min(cost[col - 1], cost[col]); } } // The last element in cost contains the minimum path cost to the bottom-right corner Ok(cost[matrix[0].len() - 1]) }
Rust-master/src/dynamic_programming/minimum_cost_path.rs
use std::cmp::min; /// Represents possible errors that can occur when calculating the minimum cost path in a matrix. #[derive(Debug, PartialEq, Eq)] pub enum MatrixError { /// Error indicating that the matrix is empty or has empty rows. EmptyMatrix, /// Error indicating that the matrix is not rectangular in shape. NonRectangularMatrix, } /// Computes the minimum cost path from the top-left to the bottom-right /// corner of a matrix, where movement is restricted to right and down directions. /// /// # Arguments /// /// * `matrix` - A 2D vector of positive integers, where each element represents /// the cost to step on that cell. /// /// # Returns /// /// * `Ok(usize)` - The minimum path cost to reach the bottom-right corner from /// the top-left corner of the matrix. /// * `Err(MatrixError)` - An error if the matrix is empty or improperly formatted. /// /// # Complexity /// /// * Time complexity: `O(m * n)`, where `m` is the number of rows /// and `n` is the number of columns in the input matrix. /// * Space complexity: `O(n)`, as only a single row of cumulative costs /// is stored at any time. pub fn minimum_cost_path(matrix: Vec<Vec<usize>>) -> Result<usize, MatrixError> { // Check if the matrix is rectangular if !matrix.iter().all(|row| row.len() == matrix[0].len()) { return Err(MatrixError::NonRectangularMatrix); } // Check if the matrix is empty or contains empty rows if matrix.is_empty() || matrix.iter().all(|row| row.is_empty()) { return Err(MatrixError::EmptyMatrix); } // Initialize the first row of the cost vector let mut cost = matrix[0] .iter() .scan(0, |acc, &val| { *acc += val; Some(*acc) }) .collect::<Vec<_>>(); // Process each row from the second to the last for row in matrix.iter().skip(1) { // Update the first element of cost for this row cost[0] += row[0]; // Update the rest of the elements in the current row of cost for col in 1..matrix[0].len() { cost[col] = row[col] + min(cost[col - 1], cost[col]); } } // The last element in cost contains the minimum path cost to the bottom-right corner Ok(cost[matrix[0].len() - 1]) } #[cfg(test)] mod tests { use super::*; macro_rules! minimum_cost_path_tests { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (matrix, expected) = $test_case; assert_eq!(minimum_cost_path(matrix), expected); } )* }; } minimum_cost_path_tests! { basic: ( vec![ vec![2, 1, 4], vec![2, 1, 3], vec![3, 2, 1] ], Ok(7) ), single_element: ( vec![ vec![5] ], Ok(5) ), single_row: ( vec![ vec![1, 3, 2, 1, 5] ], Ok(12) ), single_column: ( vec![ vec![1], vec![3], vec![2], vec![1], vec![5] ], Ok(12) ), large_matrix: ( vec![ vec![1, 3, 1, 5], vec![2, 1, 4, 2], vec![3, 2, 1, 3], vec![4, 3, 2, 1] ], Ok(10) ), uniform_matrix: ( vec![ vec![1, 1, 1], vec![1, 1, 1], vec![1, 1, 1] ], Ok(5) ), increasing_values: ( vec![ vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9] ], Ok(21) ), high_cost_path: ( vec![ vec![1, 100, 1], vec![1, 100, 1], vec![1, 1, 1] ], Ok(5) ), complex_matrix: ( vec![ vec![5, 9, 6, 8], vec![1, 4, 7, 3], vec![2, 1, 8, 2], vec![3, 6, 9, 4] ], Ok(23) ), empty_matrix: ( vec![], Err(MatrixError::EmptyMatrix) ), empty_row: ( vec![ vec![], vec![], vec![] ], Err(MatrixError::EmptyMatrix) ), non_rectangular: ( vec![ vec![1, 2, 3], vec![4, 5], vec![6, 7, 8] ], Err(MatrixError::NonRectangularMatrix) ), } }
{ "argument_definitions": [ { "definitions": [ "pub struct Vec<T, #[unstable(feature = \"allocator_api\", issue = \"32838\")] A: Allocator = Global> {\n buf: RawVec<T, A>,\n len: usize,\n}" ], "name": "weights", "type": "Vec<f64>" }, { "definitions": [ "pub struct Vec<T, #[unstable(feature = \"allocator_api\", issue = \"32838\")] A: Allocator = Global> {\n buf: RawVec<T, A>,\n len: usize,\n}" ], "name": "values", "type": "Vec<f64>" } ], "end_line": 32, "name": "fractional_knapsack", "signature": "pub fn fractional_knapsack(mut capacity: f64, weights: Vec<f64>, values: Vec<f64>) -> f64", "start_line": 1 }
fractional_knapsack
pub fn fractional_knapsack(mut capacity: f64, weights: Vec<f64>, values: Vec<f64>) -> f64 { // vector of tuple of weights and their value/weight ratio let mut weights: Vec<(f64, f64)> = weights .iter() .zip(values.iter()) .map(|(&w, &v)| (w, v / w)) .collect(); // sort in decreasing order by value/weight ratio weights.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).expect("Encountered NaN")); dbg!(&weights); // value to compute let mut knapsack_value: f64 = 0.0; // iterate through our vector. for w in weights { // w.0 is weight and w.1 value/weight ratio if w.0 < capacity { capacity -= w.0; // our sack is filling knapsack_value += w.0 * w.1; dbg!(&w.0, &knapsack_value); } else { // Multiply with capacity and not w.0 dbg!(&w.0, &knapsack_value); knapsack_value += capacity * w.1; break; } } knapsack_value }
Rust-master/src/dynamic_programming/fractional_knapsack.rs
pub fn fractional_knapsack(mut capacity: f64, weights: Vec<f64>, values: Vec<f64>) -> f64 { // vector of tuple of weights and their value/weight ratio let mut weights: Vec<(f64, f64)> = weights .iter() .zip(values.iter()) .map(|(&w, &v)| (w, v / w)) .collect(); // sort in decreasing order by value/weight ratio weights.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).expect("Encountered NaN")); dbg!(&weights); // value to compute let mut knapsack_value: f64 = 0.0; // iterate through our vector. for w in weights { // w.0 is weight and w.1 value/weight ratio if w.0 < capacity { capacity -= w.0; // our sack is filling knapsack_value += w.0 * w.1; dbg!(&w.0, &knapsack_value); } else { // Multiply with capacity and not w.0 dbg!(&w.0, &knapsack_value); knapsack_value += capacity * w.1; break; } } knapsack_value } #[cfg(test)] mod tests { use super::*; #[test] fn test() { let capacity = 50.0; let values = vec![60.0, 100.0, 120.0]; let weights = vec![10.0, 20.0, 30.0]; assert_eq!(fractional_knapsack(capacity, weights, values), 240.0); } #[test] fn test2() { let capacity = 60.0; let values = vec![280.0, 100.0, 120.0, 120.0]; let weights = vec![40.0, 10.0, 20.0, 24.0]; assert_eq!(fractional_knapsack(capacity, weights, values), 440.0); } #[test] fn test3() { let capacity = 50.0; let values = vec![60.0, 100.0, 120.0]; let weights = vec![20.0, 50.0, 30.0]; assert_eq!(fractional_knapsack(capacity, weights, values), 180.0); } #[test] fn test4() { let capacity = 60.0; let values = vec![30.0, 40.0, 45.0, 77.0, 90.0]; let weights = vec![5.0, 10.0, 15.0, 22.0, 25.0]; assert_eq!(fractional_knapsack(capacity, weights, values), 230.0); } #[test] fn test5() { let capacity = 10.0; let values = vec![500.0]; let weights = vec![30.0]; assert_eq!( format!("{:.2}", fractional_knapsack(capacity, weights, values)), String::from("166.67") ); } #[test] fn test6() { let capacity = 36.0; let values = vec![25.0, 25.0, 25.0, 6.0, 2.0]; let weights = vec![10.0, 10.0, 10.0, 4.0, 2.0]; assert_eq!(fractional_knapsack(capacity, weights, values), 83.0); } #[test] #[should_panic] fn test_nan() { let capacity = 36.0; // 2nd element is NaN let values = vec![25.0, f64::NAN, 25.0, 6.0, 2.0]; let weights = vec![10.0, 10.0, 10.0, 4.0, 2.0]; assert_eq!(fractional_knapsack(capacity, weights, values), 83.0); } }
{ "argument_definitions": [ { "definitions": [ "pub struct Vec<T, #[unstable(feature = \"allocator_api\", issue = \"32838\")] A: Allocator = Global> {\n buf: RawVec<T, A>,\n len: usize,\n}", "pub enum Colors {\n Red, // \\\n White, // | Define the three colors of the Dutch Flag: πŸ‡³πŸ‡±\n Blue, // /\n}" ], "name": "sequence", "type": "Vec<Colors>" } ], "end_line": 43, "name": "dutch_national_flag_sort", "signature": "pub fn dutch_national_flag_sort(mut sequence: Vec<Colors>) -> Vec<Colors>", "start_line": 17 }
dutch_national_flag_sort
pub fn dutch_national_flag_sort(mut sequence: Vec<Colors>) -> Vec<Colors> { // We take ownership of `sequence` because the original `sequence` will be modified and then returned let length = sequence.len(); if length <= 1 { return sequence; // Arrays of length 0 or 1 are automatically sorted } let mut low = 0; let mut mid = 0; let mut high = length - 1; while mid <= high { match sequence[mid] { Red => { sequence.swap(low, mid); low += 1; mid += 1; } White => { mid += 1; } Blue => { sequence.swap(mid, high); high -= 1; } } } sequence }
Rust-master/src/sorting/dutch_national_flag_sort.rs
/* A Rust implementation of the Dutch National Flag sorting algorithm. Reference implementation: https://github.com/TheAlgorithms/Python/blob/master/sorts/dutch_national_flag_sort.py More info: https://en.wikipedia.org/wiki/Dutch_national_flag_problem */ #[derive(PartialOrd, PartialEq, Eq)] pub enum Colors { Red, // \ White, // | Define the three colors of the Dutch Flag: πŸ‡³πŸ‡± Blue, // / } use Colors::*; // Algorithm implementation pub fn dutch_national_flag_sort(mut sequence: Vec<Colors>) -> Vec<Colors> { // We take ownership of `sequence` because the original `sequence` will be modified and then returned let length = sequence.len(); if length <= 1 { return sequence; // Arrays of length 0 or 1 are automatically sorted } let mut low = 0; let mut mid = 0; let mut high = length - 1; while mid <= high { match sequence[mid] { Red => { sequence.swap(low, mid); low += 1; mid += 1; } White => { mid += 1; } Blue => { sequence.swap(mid, high); high -= 1; } } } sequence } #[cfg(test)] mod tests { use super::super::is_sorted; use super::*; #[test] fn random_array() { let arr = vec![ Red, Blue, White, White, Blue, Blue, Red, Red, White, Blue, White, Red, White, Blue, ]; let arr = dutch_national_flag_sort(arr); assert!(is_sorted(&arr)) } #[test] fn sorted_array() { let arr = vec![ Red, Red, Red, Red, Red, White, White, White, White, White, Blue, Blue, Blue, Blue, ]; let arr = dutch_national_flag_sort(arr); assert!(is_sorted(&arr)) } }
{ "argument_definitions": [ { "definitions": [ ") -> BTreeMap<V, Option<(V, E)>> {\n let mut ans = BTreeMap::new();\n let mut prio = BTreeSet::new();\n\n // start is the special case that doesn't have a predecessor\n ans.insert(start, None);\n\n for (new, weight) in &graph[&start] {\n ans.insert(*new, Some((start, *weight)));\n prio.insert((*weight, *new));\n }\n\n while let Some((path_weight, vertex)) = prio.pop_first() {\n for (next, weight) in &graph[&vertex] {\n let new_weight = path_weight + *weight;\n match ans.get(next) {\n // if ans[next] is a lower dist than the alternative one, we do nothing\n Some(Some((_, dist_next))) if new_weight >= *dist_next => {}\n // if ans[next] is None then next is start and so the distance won't be changed, it won't be added again in prio\n Some(None) => {}\n // the new path is shorter, either new was not in ans or it was farther\n _ => {\n if let Some(Some((_, prev_weight))) =\n ans.insert(*next, Some((vertex, new_weight)))\n {\n prio.remove(&(prev_weight, *next));\n }\n prio.insert((new_weight, *next));\n }\n }\n }\n }\n\n ans\n}" ], "name": "graph", "type": "&Graph<V, E>" } ], "end_line": 52, "name": "dijkstra", "signature": "pub fn dijkstra(\n graph: &Graph<V, E>,\n start: V,\n) -> BTreeMap<V, Option<(V, E)>>", "start_line": 15 }
dijkstra
pub fn dijkstra( graph: &Graph<V, E>, start: V, ) -> BTreeMap<V, Option<(V, E)>> { let mut ans = BTreeMap::new(); let mut prio = BTreeSet::new(); // start is the special case that doesn't have a predecessor ans.insert(start, None); for (new, weight) in &graph[&start] { ans.insert(*new, Some((start, *weight))); prio.insert((*weight, *new)); } while let Some((path_weight, vertex)) = prio.pop_first() { for (next, weight) in &graph[&vertex] { let new_weight = path_weight + *weight; match ans.get(next) { // if ans[next] is a lower dist than the alternative one, we do nothing Some(Some((_, dist_next))) if new_weight >= *dist_next => {} // if ans[next] is None then next is start and so the distance won't be changed, it won't be added again in prio Some(None) => {} // the new path is shorter, either new was not in ans or it was farther _ => { if let Some(Some((_, prev_weight))) = ans.insert(*next, Some((vertex, new_weight))) { prio.remove(&(prev_weight, *next)); } prio.insert((new_weight, *next)); } } } } ans }
Rust-master/src/graph/dijkstra.rs
use std::collections::{BTreeMap, BTreeSet}; use std::ops::Add; type Graph<V, E> = BTreeMap<V, BTreeMap<V, E>>; // performs Dijsktra's algorithm on the given graph from the given start // the graph is a positively-weighted directed graph // // returns a map that for each reachable vertex associates the distance and the predecessor // since the start has no predecessor but is reachable, map[start] will be None // // Time: O(E * logV). For each vertex, we traverse each edge, resulting in O(E). For each edge, we // insert a new shortest path for a vertex into the tree, resulting in O(E * logV). // Space: O(V). The tree holds up to V vertices. pub fn dijkstra<V: Ord + Copy, E: Ord + Copy + Add<Output = E>>( graph: &Graph<V, E>, start: V, ) -> BTreeMap<V, Option<(V, E)>> { let mut ans = BTreeMap::new(); let mut prio = BTreeSet::new(); // start is the special case that doesn't have a predecessor ans.insert(start, None); for (new, weight) in &graph[&start] { ans.insert(*new, Some((start, *weight))); prio.insert((*weight, *new)); } while let Some((path_weight, vertex)) = prio.pop_first() { for (next, weight) in &graph[&vertex] { let new_weight = path_weight + *weight; match ans.get(next) { // if ans[next] is a lower dist than the alternative one, we do nothing Some(Some((_, dist_next))) if new_weight >= *dist_next => {} // if ans[next] is None then next is start and so the distance won't be changed, it won't be added again in prio Some(None) => {} // the new path is shorter, either new was not in ans or it was farther _ => { if let Some(Some((_, prev_weight))) = ans.insert(*next, Some((vertex, new_weight))) { prio.remove(&(prev_weight, *next)); } prio.insert((new_weight, *next)); } } } } ans } #[cfg(test)] mod tests { use super::{dijkstra, Graph}; use std::collections::BTreeMap; fn add_edge<V: Ord + Copy, E: Ord>(graph: &mut Graph<V, E>, v1: V, v2: V, c: E) { graph.entry(v1).or_default().insert(v2, c); graph.entry(v2).or_default(); } #[test] fn single_vertex() { let mut graph: Graph<usize, usize> = BTreeMap::new(); graph.insert(0, BTreeMap::new()); let mut dists = BTreeMap::new(); dists.insert(0, None); assert_eq!(dijkstra(&graph, 0), dists); } #[test] fn single_edge() { let mut graph = BTreeMap::new(); add_edge(&mut graph, 0, 1, 2); let mut dists_0 = BTreeMap::new(); dists_0.insert(0, None); dists_0.insert(1, Some((0, 2))); assert_eq!(dijkstra(&graph, 0), dists_0); let mut dists_1 = BTreeMap::new(); dists_1.insert(1, None); assert_eq!(dijkstra(&graph, 1), dists_1); } #[test] fn tree_1() { let mut graph = BTreeMap::new(); let mut dists = BTreeMap::new(); dists.insert(1, None); for i in 1..100 { add_edge(&mut graph, i, i * 2, i * 2); add_edge(&mut graph, i, i * 2 + 1, i * 2 + 1); match dists[&i] { Some((_, d)) => { dists.insert(i * 2, Some((i, d + i * 2))); dists.insert(i * 2 + 1, Some((i, d + i * 2 + 1))); } None => { dists.insert(i * 2, Some((i, i * 2))); dists.insert(i * 2 + 1, Some((i, i * 2 + 1))); } } } assert_eq!(dijkstra(&graph, 1), dists); } #[test] fn graph_1() { let mut graph = BTreeMap::new(); add_edge(&mut graph, 'a', 'c', 12); add_edge(&mut graph, 'a', 'd', 60); add_edge(&mut graph, 'b', 'a', 10); add_edge(&mut graph, 'c', 'b', 20); add_edge(&mut graph, 'c', 'd', 32); add_edge(&mut graph, 'e', 'a', 7); let mut dists_a = BTreeMap::new(); dists_a.insert('a', None); dists_a.insert('c', Some(('a', 12))); dists_a.insert('d', Some(('c', 44))); dists_a.insert('b', Some(('c', 32))); assert_eq!(dijkstra(&graph, 'a'), dists_a); let mut dists_b = BTreeMap::new(); dists_b.insert('b', None); dists_b.insert('a', Some(('b', 10))); dists_b.insert('c', Some(('a', 22))); dists_b.insert('d', Some(('c', 54))); assert_eq!(dijkstra(&graph, 'b'), dists_b); let mut dists_c = BTreeMap::new(); dists_c.insert('c', None); dists_c.insert('b', Some(('c', 20))); dists_c.insert('d', Some(('c', 32))); dists_c.insert('a', Some(('b', 30))); assert_eq!(dijkstra(&graph, 'c'), dists_c); let mut dists_d = BTreeMap::new(); dists_d.insert('d', None); assert_eq!(dijkstra(&graph, 'd'), dists_d); let mut dists_e = BTreeMap::new(); dists_e.insert('e', None); dists_e.insert('a', Some(('e', 7))); dists_e.insert('c', Some(('a', 19))); dists_e.insert('d', Some(('c', 51))); dists_e.insert('b', Some(('c', 39))); assert_eq!(dijkstra(&graph, 'e'), dists_e); } }
{ "argument_definitions": [ { "definitions": [ "struct Candidate<V, E> {\n estimated_weight: E,\n real_weight: E,\n state: V,\n}" ], "name": "graph", "type": "&Graph<V, E>" } ], "end_line": 99, "name": "astar", "signature": "pub fn astar(\n graph: &Graph<V, E>,\n start: V,\n target: V,\n heuristic: impl Fn(V) -> E,\n) -> Option<(E, Vec<V>)>", "start_line": 33 }
astar
pub fn astar( graph: &Graph<V, E>, start: V, target: V, heuristic: impl Fn(V) -> E, ) -> Option<(E, Vec<V>)> { // traversal front let mut queue = BinaryHeap::new(); // maps each node to its predecessor in the final path let mut previous = BTreeMap::new(); // weights[v] is the accumulated weight from start to v let mut weights = BTreeMap::new(); // initialize traversal weights.insert(start, E::zero()); queue.push(Candidate { estimated_weight: heuristic(start), real_weight: E::zero(), state: start, }); while let Some(Candidate { real_weight, state: current, .. }) = queue.pop() { if current == target { break; } for (&next, &weight) in &graph[&current] { let real_weight = real_weight + weight; if weights .get(&next) .is_none_or(|&weight| real_weight < weight) { // current allows us to reach next with lower weight (or at all) // add next to the front let estimated_weight = real_weight + heuristic(next); weights.insert(next, real_weight); queue.push(Candidate { estimated_weight, real_weight, state: next, }); previous.insert(next, current); } } } let weight = if let Some(&weight) = weights.get(&target) { weight } else { // we did not reach target from start return None; }; // build path in reverse let mut current = target; let mut path = vec![current]; while current != start { let prev = previous .get(&current) .copied() .expect("We reached the target, but are unable to reconsistute the path"); current = prev; path.push(current); } path.reverse(); Some((weight, path)) }
Rust-master/src/graph/astar.rs
use std::{ collections::{BTreeMap, BinaryHeap}, ops::Add, }; use num_traits::Zero; type Graph<V, E> = BTreeMap<V, BTreeMap<V, E>>; #[derive(Clone, Debug, Eq, PartialEq)] struct Candidate<V, E> { estimated_weight: E, real_weight: E, state: V, } impl<V: Ord + Copy, E: Ord + Copy> PartialOrd for Candidate<V, E> { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { // Note the inverted order; we want nodes with lesser weight to have // higher priority Some(self.cmp(other)) } } impl<V: Ord + Copy, E: Ord + Copy> Ord for Candidate<V, E> { fn cmp(&self, other: &Self) -> std::cmp::Ordering { // Note the inverted order; we want nodes with lesser weight to have // higher priority other.estimated_weight.cmp(&self.estimated_weight) } } pub fn astar<V: Ord + Copy, E: Ord + Copy + Add<Output = E> + Zero>( graph: &Graph<V, E>, start: V, target: V, heuristic: impl Fn(V) -> E, ) -> Option<(E, Vec<V>)> { // traversal front let mut queue = BinaryHeap::new(); // maps each node to its predecessor in the final path let mut previous = BTreeMap::new(); // weights[v] is the accumulated weight from start to v let mut weights = BTreeMap::new(); // initialize traversal weights.insert(start, E::zero()); queue.push(Candidate { estimated_weight: heuristic(start), real_weight: E::zero(), state: start, }); while let Some(Candidate { real_weight, state: current, .. }) = queue.pop() { if current == target { break; } for (&next, &weight) in &graph[&current] { let real_weight = real_weight + weight; if weights .get(&next) .is_none_or(|&weight| real_weight < weight) { // current allows us to reach next with lower weight (or at all) // add next to the front let estimated_weight = real_weight + heuristic(next); weights.insert(next, real_weight); queue.push(Candidate { estimated_weight, real_weight, state: next, }); previous.insert(next, current); } } } let weight = if let Some(&weight) = weights.get(&target) { weight } else { // we did not reach target from start return None; }; // build path in reverse let mut current = target; let mut path = vec![current]; while current != start { let prev = previous .get(&current) .copied() .expect("We reached the target, but are unable to reconsistute the path"); current = prev; path.push(current); } path.reverse(); Some((weight, path)) } #[cfg(test)] mod tests { use super::{astar, Graph}; use num_traits::Zero; use std::collections::BTreeMap; // the null heuristic make A* equivalent to Dijkstra fn null_heuristic<V, E: Zero>(_v: V) -> E { E::zero() } fn add_edge<V: Ord + Copy, E: Ord>(graph: &mut Graph<V, E>, v1: V, v2: V, c: E) { graph.entry(v1).or_default().insert(v2, c); graph.entry(v2).or_default(); } #[test] fn single_vertex() { let mut graph: Graph<usize, usize> = BTreeMap::new(); graph.insert(0, BTreeMap::new()); assert_eq!(astar(&graph, 0, 0, null_heuristic), Some((0, vec![0]))); assert_eq!(astar(&graph, 0, 1, null_heuristic), None); } #[test] fn single_edge() { let mut graph = BTreeMap::new(); add_edge(&mut graph, 0, 1, 2); assert_eq!(astar(&graph, 0, 1, null_heuristic), Some((2, vec![0, 1]))); assert_eq!(astar(&graph, 1, 0, null_heuristic), None); } #[test] fn graph_1() { let mut graph = BTreeMap::new(); add_edge(&mut graph, 'a', 'c', 12); add_edge(&mut graph, 'a', 'd', 60); add_edge(&mut graph, 'b', 'a', 10); add_edge(&mut graph, 'c', 'b', 20); add_edge(&mut graph, 'c', 'd', 32); add_edge(&mut graph, 'e', 'a', 7); // from a assert_eq!( astar(&graph, 'a', 'a', null_heuristic), Some((0, vec!['a'])) ); assert_eq!( astar(&graph, 'a', 'b', null_heuristic), Some((32, vec!['a', 'c', 'b'])) ); assert_eq!( astar(&graph, 'a', 'c', null_heuristic), Some((12, vec!['a', 'c'])) ); assert_eq!( astar(&graph, 'a', 'd', null_heuristic), Some((12 + 32, vec!['a', 'c', 'd'])) ); assert_eq!(astar(&graph, 'a', 'e', null_heuristic), None); // from b assert_eq!( astar(&graph, 'b', 'a', null_heuristic), Some((10, vec!['b', 'a'])) ); assert_eq!( astar(&graph, 'b', 'b', null_heuristic), Some((0, vec!['b'])) ); assert_eq!( astar(&graph, 'b', 'c', null_heuristic), Some((10 + 12, vec!['b', 'a', 'c'])) ); assert_eq!( astar(&graph, 'b', 'd', null_heuristic), Some((10 + 12 + 32, vec!['b', 'a', 'c', 'd'])) ); assert_eq!(astar(&graph, 'b', 'e', null_heuristic), None); // from c assert_eq!( astar(&graph, 'c', 'a', null_heuristic), Some((20 + 10, vec!['c', 'b', 'a'])) ); assert_eq!( astar(&graph, 'c', 'b', null_heuristic), Some((20, vec!['c', 'b'])) ); assert_eq!( astar(&graph, 'c', 'c', null_heuristic), Some((0, vec!['c'])) ); assert_eq!( astar(&graph, 'c', 'd', null_heuristic), Some((32, vec!['c', 'd'])) ); assert_eq!(astar(&graph, 'c', 'e', null_heuristic), None); // from d assert_eq!(astar(&graph, 'd', 'a', null_heuristic), None); assert_eq!(astar(&graph, 'd', 'b', null_heuristic), None); assert_eq!(astar(&graph, 'd', 'c', null_heuristic), None); assert_eq!( astar(&graph, 'd', 'd', null_heuristic), Some((0, vec!['d'])) ); assert_eq!(astar(&graph, 'd', 'e', null_heuristic), None); // from e assert_eq!( astar(&graph, 'e', 'a', null_heuristic), Some((7, vec!['e', 'a'])) ); assert_eq!( astar(&graph, 'e', 'b', null_heuristic), Some((7 + 12 + 20, vec!['e', 'a', 'c', 'b'])) ); assert_eq!( astar(&graph, 'e', 'c', null_heuristic), Some((7 + 12, vec!['e', 'a', 'c'])) ); assert_eq!( astar(&graph, 'e', 'd', null_heuristic), Some((7 + 12 + 32, vec!['e', 'a', 'c', 'd'])) ); assert_eq!( astar(&graph, 'e', 'e', null_heuristic), Some((0, vec!['e'])) ); } #[test] fn test_heuristic() { // make a grid let mut graph = BTreeMap::new(); let rows = 100; let cols = 100; for row in 0..rows { for col in 0..cols { add_edge(&mut graph, (row, col), (row + 1, col), 1); add_edge(&mut graph, (row, col), (row, col + 1), 1); add_edge(&mut graph, (row, col), (row + 1, col + 1), 1); add_edge(&mut graph, (row + 1, col), (row, col), 1); add_edge(&mut graph, (row + 1, col + 1), (row, col), 1); } } // Dijkstra would explore most of the 101 Γ— 101 nodes // the heuristic should allow exploring only about 200 nodes let now = std::time::Instant::now(); let res = astar(&graph, (0, 0), (100, 90), |(i, j)| 100 - i + 90 - j); assert!(now.elapsed() < std::time::Duration::from_millis(10)); let (weight, path) = res.unwrap(); assert_eq!(weight, 100); assert_eq!(path.len(), 101); } }
{ "argument_definitions": [ { "definitions": [ "pub struct Vec<T, #[unstable(feature = \"allocator_api\", issue = \"32838\")] A: Allocator = Global> {\n buf: RawVec<T, A>,\n len: usize,\n}" ], "name": "graph", "type": "&[Vec<usize>]" } ], "end_line": 140, "name": "ford_fulkerson", "signature": "pub fn ford_fulkerson(\n graph: &[Vec<usize>],\n source: usize,\n sink: usize,\n) -> Result<usize, FordFulkersonError>", "start_line": 107 }
ford_fulkerson
pub fn ford_fulkerson( graph: &[Vec<usize>], source: usize, sink: usize, ) -> Result<usize, FordFulkersonError> { validate_ford_fulkerson_input(graph, source, sink)?; let mut residual_graph = graph.to_owned(); let mut parent = vec![usize::MAX; graph.len()]; let mut max_flow = 0; while bfs(&residual_graph, source, sink, &mut parent) { let mut path_flow = usize::MAX; let mut previous_vertex = sink; while previous_vertex != source { let current_vertex = parent[previous_vertex]; path_flow = path_flow.min(residual_graph[current_vertex][previous_vertex]); previous_vertex = current_vertex; } previous_vertex = sink; while previous_vertex != source { let current_vertex = parent[previous_vertex]; residual_graph[current_vertex][previous_vertex] -= path_flow; residual_graph[previous_vertex][current_vertex] += path_flow; previous_vertex = current_vertex; } max_flow += path_flow; } Ok(max_flow) }
Rust-master/src/graph/ford_fulkerson.rs
//! The Ford-Fulkerson algorithm is a widely used algorithm to solve the maximum flow problem in a flow network. //! //! The maximum flow problem involves determining the maximum amount of flow that can be sent from a source vertex to a sink vertex //! in a directed weighted graph, subject to capacity constraints on the edges. use std::collections::VecDeque; /// Enum representing the possible errors that can occur when running the Ford-Fulkerson algorithm. #[derive(Debug, PartialEq)] pub enum FordFulkersonError { EmptyGraph, ImproperGraph, SourceOutOfBounds, SinkOutOfBounds, } /// Performs a Breadth-First Search (BFS) on the residual graph to find an augmenting path /// from the source vertex `source` to the sink vertex `sink`. /// /// # Arguments /// /// * `graph` - A reference to the residual graph represented as an adjacency matrix. /// * `source` - The source vertex. /// * `sink` - The sink vertex. /// * `parent` - A mutable reference to the parent array used to store the augmenting path. /// /// # Returns /// /// Returns `true` if an augmenting path is found from `source` to `sink`, `false` otherwise. fn bfs(graph: &[Vec<usize>], source: usize, sink: usize, parent: &mut [usize]) -> bool { let mut visited = vec![false; graph.len()]; visited[source] = true; parent[source] = usize::MAX; let mut queue = VecDeque::new(); queue.push_back(source); while let Some(current_vertex) = queue.pop_front() { for (previous_vertex, &capacity) in graph[current_vertex].iter().enumerate() { if !visited[previous_vertex] && capacity > 0 { visited[previous_vertex] = true; parent[previous_vertex] = current_vertex; if previous_vertex == sink { return true; } queue.push_back(previous_vertex); } } } false } /// Validates the input parameters for the Ford-Fulkerson algorithm. /// /// This function checks if the provided graph, source vertex, and sink vertex /// meet the requirements for the Ford-Fulkerson algorithm. It ensures the graph /// is non-empty, square (each row has the same length as the number of rows), and /// that the source and sink vertices are within the valid range of vertex indices. /// /// # Arguments /// /// * `graph` - A reference to the flow network represented as an adjacency matrix. /// * `source` - The source vertex. /// * `sink` - The sink vertex. /// /// # Returns /// /// Returns `Ok(())` if the input parameters are valid, otherwise returns an appropriate /// `FordFulkersonError`. fn validate_ford_fulkerson_input( graph: &[Vec<usize>], source: usize, sink: usize, ) -> Result<(), FordFulkersonError> { if graph.is_empty() { return Err(FordFulkersonError::EmptyGraph); } if graph.iter().any(|row| row.len() != graph.len()) { return Err(FordFulkersonError::ImproperGraph); } if source >= graph.len() { return Err(FordFulkersonError::SourceOutOfBounds); } if sink >= graph.len() { return Err(FordFulkersonError::SinkOutOfBounds); } Ok(()) } /// Applies the Ford-Fulkerson algorithm to find the maximum flow in a flow network /// represented by a weighted directed graph. /// /// # Arguments /// /// * `graph` - A mutable reference to the flow network represented as an adjacency matrix. /// * `source` - The source vertex. /// * `sink` - The sink vertex. /// /// # Returns /// /// Returns the maximum flow and the residual graph pub fn ford_fulkerson( graph: &[Vec<usize>], source: usize, sink: usize, ) -> Result<usize, FordFulkersonError> { validate_ford_fulkerson_input(graph, source, sink)?; let mut residual_graph = graph.to_owned(); let mut parent = vec![usize::MAX; graph.len()]; let mut max_flow = 0; while bfs(&residual_graph, source, sink, &mut parent) { let mut path_flow = usize::MAX; let mut previous_vertex = sink; while previous_vertex != source { let current_vertex = parent[previous_vertex]; path_flow = path_flow.min(residual_graph[current_vertex][previous_vertex]); previous_vertex = current_vertex; } previous_vertex = sink; while previous_vertex != source { let current_vertex = parent[previous_vertex]; residual_graph[current_vertex][previous_vertex] -= path_flow; residual_graph[previous_vertex][current_vertex] += path_flow; previous_vertex = current_vertex; } max_flow += path_flow; } Ok(max_flow) } #[cfg(test)] mod tests { use super::*; macro_rules! test_max_flow { ($($name:ident: $tc:expr,)* ) => { $( #[test] fn $name() { let (graph, source, sink, expected_result) = $tc; assert_eq!(ford_fulkerson(&graph, source, sink), expected_result); } )* }; } test_max_flow! { test_empty_graph: ( vec![], 0, 0, Err(FordFulkersonError::EmptyGraph), ), test_source_out_of_bound: ( vec![ vec![0, 8, 0, 0, 3, 0], vec![0, 0, 9, 0, 0, 0], vec![0, 0, 0, 0, 7, 2], vec![0, 0, 0, 0, 0, 5], vec![0, 0, 7, 4, 0, 0], vec![0, 0, 0, 0, 0, 0], ], 6, 5, Err(FordFulkersonError::SourceOutOfBounds), ), test_sink_out_of_bound: ( vec![ vec![0, 8, 0, 0, 3, 0], vec![0, 0, 9, 0, 0, 0], vec![0, 0, 0, 0, 7, 2], vec![0, 0, 0, 0, 0, 5], vec![0, 0, 7, 4, 0, 0], vec![0, 0, 0, 0, 0, 0], ], 0, 6, Err(FordFulkersonError::SinkOutOfBounds), ), test_improper_graph: ( vec![ vec![0, 8], vec![0], ], 0, 1, Err(FordFulkersonError::ImproperGraph), ), test_graph_with_small_flow: ( vec![ vec![0, 8, 0, 0, 3, 0], vec![0, 0, 9, 0, 0, 0], vec![0, 0, 0, 0, 7, 2], vec![0, 0, 0, 0, 0, 5], vec![0, 0, 7, 4, 0, 0], vec![0, 0, 0, 0, 0, 0], ], 0, 5, Ok(6), ), test_graph_with_medium_flow: ( vec![ vec![0, 10, 0, 10, 0, 0], vec![0, 0, 4, 2, 8, 0], vec![0, 0, 0, 0, 0, 10], vec![0, 0, 0, 0, 9, 0], vec![0, 0, 6, 0, 0, 10], vec![0, 0, 0, 0, 0, 0], ], 0, 5, Ok(19), ), test_graph_with_large_flow: ( vec![ vec![0, 12, 0, 13, 0, 0], vec![0, 0, 10, 0, 0, 0], vec![0, 0, 0, 13, 3, 15], vec![0, 0, 7, 0, 15, 0], vec![0, 0, 6, 0, 0, 17], vec![0, 0, 0, 0, 0, 0], ], 0, 5, Ok(23), ), test_complex_graph: ( vec![ vec![0, 16, 13, 0, 0, 0], vec![0, 0, 10, 12, 0, 0], vec![0, 4, 0, 0, 14, 0], vec![0, 0, 9, 0, 0, 20], vec![0, 0, 0, 7, 0, 4], vec![0, 0, 0, 0, 0, 0], ], 0, 5, Ok(23), ), test_disconnected_graph: ( vec![ vec![0, 0, 0, 0], vec![0, 0, 0, 1], vec![0, 0, 0, 1], vec![0, 0, 0, 0], ], 0, 3, Ok(0), ), test_unconnected_sink: ( vec![ vec![0, 4, 0, 3, 0, 0], vec![0, 0, 4, 0, 8, 0], vec![0, 0, 0, 3, 0, 2], vec![0, 0, 0, 0, 6, 0], vec![0, 0, 6, 0, 0, 6], vec![0, 0, 0, 0, 0, 0], ], 0, 5, Ok(7), ), test_no_edges: ( vec![ vec![0, 0, 0], vec![0, 0, 0], vec![0, 0, 0], ], 0, 2, Ok(0), ), test_single_vertex: ( vec![ vec![0], ], 0, 0, Ok(0), ), test_self_loop: ( vec![ vec![10, 0], vec![0, 0], ], 0, 1, Ok(0), ), test_same_source_sink: ( vec![ vec![0, 10, 10], vec![0, 0, 10], vec![0, 0, 0], ], 0, 0, Ok(0), ), } }
{ "argument_definitions": [ { "definitions": [ "pub struct Graph {\n #[allow(dead_code)]\n nodes: Vec<Node>,\n edges: Vec<Edge>,\n}" ], "name": "graph", "type": "&Graph" }, { "definitions": [ "pub struct Graph {\n #[allow(dead_code)]\n nodes: Vec<Node>,\n edges: Vec<Edge>,\n}" ], "name": "root", "type": "Node" }, { "definitions": [ "pub struct Graph {\n #[allow(dead_code)]\n nodes: Vec<Node>,\n edges: Vec<Edge>,\n}" ], "name": "target", "type": "Node" } ], "end_line": 45, "name": "breadth_first_search", "signature": "pub fn breadth_first_search(graph: &Graph, root: Node, target: Node) -> Option<Vec<u32>>", "start_line": 20 }
breadth_first_search
pub fn breadth_first_search(graph: &Graph, root: Node, target: Node) -> Option<Vec<u32>> { let mut visited: HashSet<Node> = HashSet::new(); let mut history: Vec<u32> = Vec::new(); let mut queue = VecDeque::new(); visited.insert(root); queue.push_back(root); while let Some(currentnode) = queue.pop_front() { history.push(currentnode.value()); // If we reach the goal, return our travel history. if currentnode == target { return Some(history); } // Check the neighboring nodes for any that we've not visited yet. for neighbor in currentnode.neighbors(graph) { if visited.insert(neighbor) { queue.push_back(neighbor); } } } // All nodes were visited, yet the target was not found. None }
Rust-master/src/graph/breadth_first_search.rs
use std::collections::HashSet; use std::collections::VecDeque; /// Perform a breadth-first search on Graph `graph`. /// /// # Parameters /// /// - `graph`: The graph to search. /// - `root`: The starting node of the graph from which to begin searching. /// - `target`: The target node for the search. /// /// # Returns /// /// If the target is found, an Optional vector is returned with the history /// of nodes visited as its contents. /// /// If the target is not found or there is no path from the root, /// `None` is returned. /// pub fn breadth_first_search(graph: &Graph, root: Node, target: Node) -> Option<Vec<u32>> { let mut visited: HashSet<Node> = HashSet::new(); let mut history: Vec<u32> = Vec::new(); let mut queue = VecDeque::new(); visited.insert(root); queue.push_back(root); while let Some(currentnode) = queue.pop_front() { history.push(currentnode.value()); // If we reach the goal, return our travel history. if currentnode == target { return Some(history); } // Check the neighboring nodes for any that we've not visited yet. for neighbor in currentnode.neighbors(graph) { if visited.insert(neighbor) { queue.push_back(neighbor); } } } // All nodes were visited, yet the target was not found. None } // Data Structures #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Node(u32); #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Edge(u32, u32); #[derive(Clone)] pub struct Graph { #[allow(dead_code)] nodes: Vec<Node>, edges: Vec<Edge>, } impl Graph { pub fn new(nodes: Vec<Node>, edges: Vec<Edge>) -> Self { Graph { nodes, edges } } } impl From<u32> for Node { fn from(item: u32) -> Self { Node(item) } } impl Node { pub fn value(&self) -> u32 { self.0 } pub fn neighbors(&self, graph: &Graph) -> Vec<Node> { graph .edges .iter() .filter(|e| e.0 == self.0) .map(|e| e.1.into()) .collect() } } impl From<(u32, u32)> for Edge { fn from(item: (u32, u32)) -> Self { Edge(item.0, item.1) } } #[cfg(test)] mod tests { use super::*; /* Example graph #1: * * (1) <--- Root * / \ * (2) (3) * / | | \ * (4) (5) (6) (7) * | * (8) */ fn graph1() -> Graph { let nodes = vec![1, 2, 3, 4, 5, 6, 7]; let edges = vec![(1, 2), (1, 3), (2, 4), (2, 5), (3, 6), (3, 7), (5, 8)]; Graph::new( nodes.into_iter().map(|v| v.into()).collect(), edges.into_iter().map(|e| e.into()).collect(), ) } #[test] fn breadth_first_search_graph1_when_node_not_found_returns_none() { let graph = graph1(); let root = 1; let target = 10; assert_eq!( breadth_first_search(&graph, root.into(), target.into()), None ); } #[test] fn breadth_first_search_graph1_when_target_8_should_evaluate_all_nodes_first() { let graph = graph1(); let root = 1; let target = 8; let expected_path = vec![1, 2, 3, 4, 5, 6, 7, 8]; assert_eq!( breadth_first_search(&graph, root.into(), target.into()), Some(expected_path) ); } /* Example graph #2: * * (1) --- (2) (3) --- (4) * / | / / * / | / / * / | / / * (5) (6) --- (7) (8) */ fn graph2() -> Graph { let nodes = vec![1, 2, 3, 4, 5, 6, 7, 8]; let undirected_edges = vec![ (1, 2), (2, 1), (2, 5), (5, 2), (2, 6), (6, 2), (3, 4), (4, 3), (3, 6), (6, 3), (4, 7), (7, 4), (6, 7), (7, 6), ]; Graph::new( nodes.into_iter().map(|v| v.into()).collect(), undirected_edges.into_iter().map(|e| e.into()).collect(), ) } #[test] fn breadth_first_search_graph2_when_no_path_to_node_returns_none() { let graph = graph2(); let root = 8; let target = 4; assert_eq!( breadth_first_search(&graph, root.into(), target.into()), None ); } #[test] fn breadth_first_search_graph2_should_find_path_from_4_to_1() { let graph = graph2(); let root = 4; let target = 1; let expected_path = vec![4, 3, 7, 6, 2, 1]; assert_eq!( breadth_first_search(&graph, root.into(), target.into()), Some(expected_path) ); } }
{ "argument_definitions": [ { "definitions": [ "pub struct Graph {\n #[allow(dead_code)]\n vertices: Vec<Vertex>,\n edges: Vec<Edge>,\n}" ], "name": "graph", "type": "&Graph" }, { "definitions": [ "pub struct Graph {\n #[allow(dead_code)]\n vertices: Vec<Vertex>,\n edges: Vec<Edge>,\n}" ], "name": "root", "type": "Vertex" }, { "definitions": [ "pub struct Graph {\n #[allow(dead_code)]\n vertices: Vec<Vertex>,\n edges: Vec<Edge>,\n}" ], "name": "objective", "type": "Vertex" } ], "end_line": 39, "name": "depth_first_search", "signature": "pub fn depth_first_search(graph: &Graph, root: Vertex, objective: Vertex) -> Option<Vec<u32>>", "start_line": 8 }
depth_first_search
pub fn depth_first_search(graph: &Graph, root: Vertex, objective: Vertex) -> Option<Vec<u32>> { let mut visited: HashSet<Vertex> = HashSet::new(); let mut history: Vec<u32> = Vec::new(); let mut queue = VecDeque::new(); queue.push_back(root); // While there is an element in the queue // get the first element of the vertex queue while let Some(current_vertex) = queue.pop_front() { // Added current vertex in the history of visiteds vertex history.push(current_vertex.value()); // Verify if this vertex is the objective if current_vertex == objective { // Return the Optional with the history of visiteds vertex return Some(history); } // For each over the neighbors of current vertex for neighbor in current_vertex.neighbors(graph).into_iter().rev() { // Insert in the HashSet of visiteds if this value not exist yet if visited.insert(neighbor) { // Add the neighbor on front of queue queue.push_front(neighbor); } } } // If all vertex is visited and the objective is not found // return a Optional with None value None }
Rust-master/src/graph/depth_first_search.rs
use std::collections::HashSet; use std::collections::VecDeque; // Perform a Depth First Search Algorithm to find a element in a graph // // Return a Optional with a vector with history of vertex visiteds // or a None if the element not exists on the graph pub fn depth_first_search(graph: &Graph, root: Vertex, objective: Vertex) -> Option<Vec<u32>> { let mut visited: HashSet<Vertex> = HashSet::new(); let mut history: Vec<u32> = Vec::new(); let mut queue = VecDeque::new(); queue.push_back(root); // While there is an element in the queue // get the first element of the vertex queue while let Some(current_vertex) = queue.pop_front() { // Added current vertex in the history of visiteds vertex history.push(current_vertex.value()); // Verify if this vertex is the objective if current_vertex == objective { // Return the Optional with the history of visiteds vertex return Some(history); } // For each over the neighbors of current vertex for neighbor in current_vertex.neighbors(graph).into_iter().rev() { // Insert in the HashSet of visiteds if this value not exist yet if visited.insert(neighbor) { // Add the neighbor on front of queue queue.push_front(neighbor); } } } // If all vertex is visited and the objective is not found // return a Optional with None value None } // Data Structures #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Vertex(u32); #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Edge(u32, u32); #[derive(Clone)] pub struct Graph { #[allow(dead_code)] vertices: Vec<Vertex>, edges: Vec<Edge>, } impl Graph { pub fn new(vertices: Vec<Vertex>, edges: Vec<Edge>) -> Self { Graph { vertices, edges } } } impl From<u32> for Vertex { fn from(item: u32) -> Self { Vertex(item) } } impl Vertex { pub fn value(&self) -> u32 { self.0 } pub fn neighbors(&self, graph: &Graph) -> VecDeque<Vertex> { graph .edges .iter() .filter(|e| e.0 == self.0) .map(|e| e.1.into()) .collect() } } impl From<(u32, u32)> for Edge { fn from(item: (u32, u32)) -> Self { Edge(item.0, item.1) } } #[cfg(test)] mod tests { use super::*; #[test] fn find_1_fail() { let vertices = vec![1, 2, 3, 4, 5, 6, 7]; let edges = vec![(1, 2), (1, 3), (2, 4), (2, 5), (3, 6), (3, 7)]; let root = 1; let objective = 99; let graph = Graph::new( vertices.into_iter().map(|v| v.into()).collect(), edges.into_iter().map(|e| e.into()).collect(), ); assert_eq!( depth_first_search(&graph, root.into(), objective.into()), None ); } #[test] fn find_1_sucess() { let vertices = vec![1, 2, 3, 4, 5, 6, 7]; let edges = vec![(1, 2), (1, 3), (2, 4), (2, 5), (3, 6), (3, 7)]; let root = 1; let objective = 7; let correct_path = vec![1, 2, 4, 5, 3, 6, 7]; let graph = Graph::new( vertices.into_iter().map(|v| v.into()).collect(), edges.into_iter().map(|e| e.into()).collect(), ); assert_eq!( depth_first_search(&graph, root.into(), objective.into()), Some(correct_path) ); } #[test] fn find_2_sucess() { let vertices = vec![0, 1, 2, 3, 4, 5, 6, 7]; let edges = vec![ (0, 1), (1, 3), (3, 2), (2, 1), (3, 4), (4, 5), (5, 7), (7, 6), (6, 4), ]; let root = 0; let objective = 6; let correct_path = vec![0, 1, 3, 2, 4, 5, 7, 6]; let graph = Graph::new( vertices.into_iter().map(|v| v.into()).collect(), edges.into_iter().map(|e| e.into()).collect(), ); assert_eq!( depth_first_search(&graph, root.into(), objective.into()), Some(correct_path) ); } #[test] fn find_3_sucess() { let vertices = vec![0, 1, 2, 3, 4, 5, 6, 7]; let edges = vec![ (0, 1), (1, 3), (3, 2), (2, 1), (3, 4), (4, 5), (5, 7), (7, 6), (6, 4), ]; let root = 0; let objective = 4; let correct_path = vec![0, 1, 3, 2, 4]; let graph = Graph::new( vertices.into_iter().map(|v| v.into()).collect(), edges.into_iter().map(|e| e.into()).collect(), ); assert_eq!( depth_first_search(&graph, root.into(), objective.into()), Some(correct_path) ); } }
{ "argument_definitions": [ { "definitions": [ "pub struct String {\n vec: Vec<u8>,\n}" ], "name": "s", "type": "String" } ], "end_line": 76, "name": "manacher", "signature": "pub fn manacher(s: String) -> String", "start_line": 1 }
manacher
pub fn manacher(s: String) -> String { let l = s.len(); if l <= 1 { return s; } // MEMO: We need to detect odd palindrome as well, // therefore, inserting dummy string so that // we can find a pair with dummy center character. let mut chars: Vec<char> = Vec::with_capacity(s.len() * 2 + 1); for c in s.chars() { chars.push('#'); chars.push(c); } chars.push('#'); // List: storing the length of palindrome at each index of string let mut length_of_palindrome = vec![1usize; chars.len()]; // Integer: Current checking palindrome's center index let mut current_center: usize = 0; // Integer: Right edge index existing the radius away from current center let mut right_from_current_center: usize = 0; for i in 0..chars.len() { // 1: Check if we are looking at right side of palindrome. if right_from_current_center > i && i > current_center { // 1-1: If so copy from the left side of palindrome. // If the value + index exceeds the right edge index, we should cut and check palindrome later #3. length_of_palindrome[i] = std::cmp::min( right_from_current_center - i, length_of_palindrome[2 * current_center - i], ); // 1-2: Move the checking palindrome to new index if it exceeds the right edge. if length_of_palindrome[i] + i >= right_from_current_center { current_center = i; right_from_current_center = length_of_palindrome[i] + i; // 1-3: If radius exceeds the end of list, it means checking is over. // You will never get the larger value because the string will get only shorter. if right_from_current_center >= chars.len() - 1 { break; } } else { // 1-4: If the checking index doesn't exceeds the right edge, // it means the length is just as same as the left side. // You don't need to check anymore. continue; } } // Integer: Current radius from checking index // If it's copied from left side and more than 1, // it means it's ensured so you don't need to check inside radius. let mut radius: usize = (length_of_palindrome[i] - 1) / 2; radius += 1; // 2: Checking palindrome. // Need to care about overflow usize. while i >= radius && i + radius <= chars.len() - 1 && chars[i - radius] == chars[i + radius] { length_of_palindrome[i] += 2; radius += 1; } } // 3: Find the maximum length and generate answer. let center_of_max = length_of_palindrome .iter() .enumerate() .max_by_key(|(_, &value)| value) .map(|(idx, _)| idx) .unwrap(); let radius_of_max = (length_of_palindrome[center_of_max] - 1) / 2; let answer = &chars[(center_of_max - radius_of_max)..=(center_of_max + radius_of_max)] .iter() .collect::<String>(); answer.replace('#', "") }
Rust-master/src/string/manacher.rs
pub fn manacher(s: String) -> String { let l = s.len(); if l <= 1 { return s; } // MEMO: We need to detect odd palindrome as well, // therefore, inserting dummy string so that // we can find a pair with dummy center character. let mut chars: Vec<char> = Vec::with_capacity(s.len() * 2 + 1); for c in s.chars() { chars.push('#'); chars.push(c); } chars.push('#'); // List: storing the length of palindrome at each index of string let mut length_of_palindrome = vec![1usize; chars.len()]; // Integer: Current checking palindrome's center index let mut current_center: usize = 0; // Integer: Right edge index existing the radius away from current center let mut right_from_current_center: usize = 0; for i in 0..chars.len() { // 1: Check if we are looking at right side of palindrome. if right_from_current_center > i && i > current_center { // 1-1: If so copy from the left side of palindrome. // If the value + index exceeds the right edge index, we should cut and check palindrome later #3. length_of_palindrome[i] = std::cmp::min( right_from_current_center - i, length_of_palindrome[2 * current_center - i], ); // 1-2: Move the checking palindrome to new index if it exceeds the right edge. if length_of_palindrome[i] + i >= right_from_current_center { current_center = i; right_from_current_center = length_of_palindrome[i] + i; // 1-3: If radius exceeds the end of list, it means checking is over. // You will never get the larger value because the string will get only shorter. if right_from_current_center >= chars.len() - 1 { break; } } else { // 1-4: If the checking index doesn't exceeds the right edge, // it means the length is just as same as the left side. // You don't need to check anymore. continue; } } // Integer: Current radius from checking index // If it's copied from left side and more than 1, // it means it's ensured so you don't need to check inside radius. let mut radius: usize = (length_of_palindrome[i] - 1) / 2; radius += 1; // 2: Checking palindrome. // Need to care about overflow usize. while i >= radius && i + radius <= chars.len() - 1 && chars[i - radius] == chars[i + radius] { length_of_palindrome[i] += 2; radius += 1; } } // 3: Find the maximum length and generate answer. let center_of_max = length_of_palindrome .iter() .enumerate() .max_by_key(|(_, &value)| value) .map(|(idx, _)| idx) .unwrap(); let radius_of_max = (length_of_palindrome[center_of_max] - 1) / 2; let answer = &chars[(center_of_max - radius_of_max)..=(center_of_max + radius_of_max)] .iter() .collect::<String>(); answer.replace('#', "") } #[cfg(test)] mod tests { use super::manacher; #[test] fn get_longest_palindrome_by_manacher() { assert_eq!(manacher("babad".to_string()), "aba".to_string()); assert_eq!(manacher("cbbd".to_string()), "bb".to_string()); assert_eq!(manacher("a".to_string()), "a".to_string()); let ac_ans = manacher("ac".to_string()); assert!(ac_ans == *"a" || ac_ans == *"c"); } }
{ "argument_definitions": [], "end_line": 52, "name": "kth_smallest_heap", "signature": "pub fn kth_smallest_heap(input: &[T], k: usize) -> Option<T>", "start_line": 13 }
kth_smallest_heap
pub fn kth_smallest_heap(input: &[T], k: usize) -> Option<T> { if input.len() < k { return None; } // heap will maintain the kth smallest elements // seen so far, when new elements, E_new arrives, // it is compared with the largest element of the // current Heap E_large, which is the current kth // smallest elements. // if E_new > E_large, then E_new cannot be the kth // smallest because there are already k elements smaller // than it // otherwise, E_large cannot be the kth smallest, and should // be removed from the heap and E_new should be added let mut heap = Heap::new_max(); // first k elements goes to the heap as the baseline for &val in input.iter().take(k) { heap.add(val); } for &val in input.iter().skip(k) { // compare new value to the current kth smallest value let cur_big = heap.pop().unwrap(); // heap.pop() can't be None match val.cmp(&cur_big) { Ordering::Greater => { heap.add(cur_big); } _ => { heap.add(val); } } } heap.pop() }
Rust-master/src/searching/kth_smallest_heap.rs
use crate::data_structures::Heap; use std::cmp::{Ord, Ordering}; /// Returns k-th smallest element of an array. /// Time complexity is stably O(nlog(k)) in all cases /// Extra space is required to maintain the heap, and it doesn't /// mutate the input list. /// /// It is preferrable to the partition-based algorithm in cases when /// we want to maintain the kth smallest element dynamically against /// a stream of elements. In that case, once the heap is built, further /// operation's complexity is O(log(k)). pub fn kth_smallest_heap<T>(input: &[T], k: usize) -> Option<T> where T: Ord + Copy, { if input.len() < k { return None; } // heap will maintain the kth smallest elements // seen so far, when new elements, E_new arrives, // it is compared with the largest element of the // current Heap E_large, which is the current kth // smallest elements. // if E_new > E_large, then E_new cannot be the kth // smallest because there are already k elements smaller // than it // otherwise, E_large cannot be the kth smallest, and should // be removed from the heap and E_new should be added let mut heap = Heap::new_max(); // first k elements goes to the heap as the baseline for &val in input.iter().take(k) { heap.add(val); } for &val in input.iter().skip(k) { // compare new value to the current kth smallest value let cur_big = heap.pop().unwrap(); // heap.pop() can't be None match val.cmp(&cur_big) { Ordering::Greater => { heap.add(cur_big); } _ => { heap.add(val); } } } heap.pop() } #[cfg(test)] mod tests { use super::*; #[test] fn empty() { let zero: [u8; 0] = []; let first = kth_smallest_heap(&zero, 1); assert_eq!(None, first); } #[test] fn one_element() { let one = [1]; let first = kth_smallest_heap(&one, 1); assert_eq!(1, first.unwrap()); } #[test] fn many_elements() { // 0 1 3 4 5 7 8 9 9 10 12 13 16 17 let many = [9, 17, 3, 16, 13, 10, 1, 5, 7, 12, 4, 8, 9, 0]; let first = kth_smallest_heap(&many, 1); let third = kth_smallest_heap(&many, 3); let sixth = kth_smallest_heap(&many, 6); let fourteenth = kth_smallest_heap(&many, 14); assert_eq!(0, first.unwrap()); assert_eq!(3, third.unwrap()); assert_eq!(7, sixth.unwrap()); assert_eq!(17, fourteenth.unwrap()); } }
{ "argument_definitions": [], "end_line": 37, "name": "compute_totient", "signature": "pub fn compute_totient(n: i32) -> vec::Vec<i32>", "start_line": 11 }
compute_totient
pub fn compute_totient(n: i32) -> vec::Vec<i32> { let mut phi: Vec<i32> = Vec::new(); // initialize phi[i] = i for i in 0..=n { phi.push(i); } // Compute other Phi values for p in 2..=n { // If phi[p] is not computed already, // then number p is prime if phi[(p) as usize] == p { // Phi of a prime number p is // always equal to p-1. phi[(p) as usize] = p - 1; // Update phi values of all // multiples of p for i in ((2 * p)..=n).step_by(p as usize) { phi[(i) as usize] = (phi[i as usize] / p) * (p - 1); } } } phi[1..].to_vec() }
Rust-master/src/number_theory/compute_totient.rs
// Totient function for // all numbers smaller than // or equal to n. // Computes and prints // totient of all numbers // smaller than or equal to n use std::vec; pub fn compute_totient(n: i32) -> vec::Vec<i32> { let mut phi: Vec<i32> = Vec::new(); // initialize phi[i] = i for i in 0..=n { phi.push(i); } // Compute other Phi values for p in 2..=n { // If phi[p] is not computed already, // then number p is prime if phi[(p) as usize] == p { // Phi of a prime number p is // always equal to p-1. phi[(p) as usize] = p - 1; // Update phi values of all // multiples of p for i in ((2 * p)..=n).step_by(p as usize) { phi[(i) as usize] = (phi[i as usize] / p) * (p - 1); } } } phi[1..].to_vec() } #[cfg(test)] mod tests { use super::*; #[test] fn test_1() { assert_eq!( compute_totient(12), vec![1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10, 4] ); } #[test] fn test_2() { assert_eq!(compute_totient(7), vec![1, 1, 2, 2, 4, 2, 6]); } #[test] fn test_3() { assert_eq!(compute_totient(4), vec![1, 1, 2, 2]); } }
{ "argument_definitions": [], "end_line": 60, "name": "fast_factorial", "signature": "pub fn fast_factorial(n: usize) -> BigUint", "start_line": 25 }
fast_factorial
pub fn fast_factorial(n: usize) -> BigUint { if n < 2 { return BigUint::one(); } // get list of primes that will be factors of n! let primes = sieve_of_eratosthenes(n); // Map the primes with their index let p_indices = primes .into_iter() .map(|p| (p, index(p, n))) .collect::<BTreeMap<_, _>>(); let max_bits = p_indices[&2].next_power_of_two().ilog2() + 1; // Create a Vec of 1's let mut a = vec![BigUint::one(); max_bits as usize]; // For every prime p, multiply a[i] by p if the ith bit of p's index is 1 for (p, i) in p_indices { let mut bit = 1usize; while bit.ilog2() < max_bits { if (bit & i) > 0 { a[bit.ilog2() as usize] *= p; } bit <<= 1; } } a.into_iter() .enumerate() .map(|(i, a_i)| a_i.pow(2u32.pow(i as u32))) // raise every a[i] to the 2^ith power .product() // we get our answer by multiplying the result }
Rust-master/src/big_integer/fast_factorial.rs
// Algorithm created by Peter Borwein in 1985 // https://doi.org/10.1016/0196-6774(85)90006-9 use crate::math::sieve_of_eratosthenes; use num_bigint::BigUint; use num_traits::One; use std::collections::BTreeMap; /// Calculate the sum of n / p^i with integer division for all values of i fn index(p: usize, n: usize) -> usize { let mut index = 0; let mut i = 1; let mut quot = n / p; while quot > 0 { index += quot; i += 1; quot = n / p.pow(i); } index } /// Calculate the factorial with time complexity O(log(log(n)) * M(n * log(n))) where M(n) is the time complexity of multiplying two n-digit numbers together. pub fn fast_factorial(n: usize) -> BigUint { if n < 2 { return BigUint::one(); } // get list of primes that will be factors of n! let primes = sieve_of_eratosthenes(n); // Map the primes with their index let p_indices = primes .into_iter() .map(|p| (p, index(p, n))) .collect::<BTreeMap<_, _>>(); let max_bits = p_indices[&2].next_power_of_two().ilog2() + 1; // Create a Vec of 1's let mut a = vec![BigUint::one(); max_bits as usize]; // For every prime p, multiply a[i] by p if the ith bit of p's index is 1 for (p, i) in p_indices { let mut bit = 1usize; while bit.ilog2() < max_bits { if (bit & i) > 0 { a[bit.ilog2() as usize] *= p; } bit <<= 1; } } a.into_iter() .enumerate() .map(|(i, a_i)| a_i.pow(2u32.pow(i as u32))) // raise every a[i] to the 2^ith power .product() // we get our answer by multiplying the result } #[cfg(test)] mod tests { use super::*; use crate::math::factorial::factorial_bigmath; #[test] fn fact() { assert_eq!(fast_factorial(0), BigUint::one()); assert_eq!(fast_factorial(1), BigUint::one()); assert_eq!(fast_factorial(2), factorial_bigmath(2)); assert_eq!(fast_factorial(3), factorial_bigmath(3)); assert_eq!(fast_factorial(6), factorial_bigmath(6)); assert_eq!(fast_factorial(7), factorial_bigmath(7)); assert_eq!(fast_factorial(10), factorial_bigmath(10)); assert_eq!(fast_factorial(11), factorial_bigmath(11)); assert_eq!(fast_factorial(18), factorial_bigmath(18)); assert_eq!(fast_factorial(19), factorial_bigmath(19)); assert_eq!(fast_factorial(30), factorial_bigmath(30)); assert_eq!(fast_factorial(34), factorial_bigmath(34)); assert_eq!(fast_factorial(35), factorial_bigmath(35)); assert_eq!(fast_factorial(52), factorial_bigmath(52)); assert_eq!(fast_factorial(100), factorial_bigmath(100)); assert_eq!(fast_factorial(1000), factorial_bigmath(1000)); assert_eq!(fast_factorial(5000), factorial_bigmath(5000)); } }
{ "argument_definitions": [], "end_line": 59, "name": "transposition", "signature": "pub fn transposition(decrypt_mode: bool, msg: &str, key: &str) -> String", "start_line": 12 }
transposition
pub fn transposition(decrypt_mode: bool, msg: &str, key: &str) -> String { let key_uppercase = key.to_uppercase(); let mut cipher_msg: String = msg.to_string(); let keys: Vec<&str> = if decrypt_mode { key_uppercase.split_whitespace().rev().collect() } else { key_uppercase.split_whitespace().collect() }; for cipher_key in keys.iter() { let mut key_order: Vec<usize> = Vec::new(); // Removes any non-alphabet characters from 'msg' cipher_msg = cipher_msg .to_uppercase() .chars() .filter(|&c| c.is_ascii_alphabetic()) .collect(); // Determines the sequence of the columns, as dictated by the // alphabetical order of the keyword's letters let mut key_ascii: Vec<(usize, u8)> = cipher_key.bytes().enumerate().collect::<Vec<(usize, u8)>>(); key_ascii.sort_by_key(|&(_, key)| key); for (counter, (_, key)) in key_ascii.iter_mut().enumerate() { *key = counter as u8; } key_ascii.sort_by_key(|&(index, _)| index); key_ascii .into_iter() .for_each(|(_, key)| key_order.push(key.into())); // Determines whether to encrypt or decrypt the message, // and returns the result cipher_msg = if decrypt_mode { decrypt(cipher_msg, key_order) } else { encrypt(cipher_msg, key_order) }; } cipher_msg }
Rust-master/src/ciphers/transposition.rs
//! Transposition Cipher //! //! The Transposition Cipher is a method of encryption by which a message is shifted //! according to a regular system, so that the ciphertext is a rearrangement of the //! original message. The most commonly referred to Transposition Cipher is the //! COLUMNAR TRANSPOSITION cipher, which is demonstrated below. use std::ops::RangeInclusive; /// Encrypts or decrypts a message, using multiple keys. The /// encryption is based on the columnar transposition method. pub fn transposition(decrypt_mode: bool, msg: &str, key: &str) -> String { let key_uppercase = key.to_uppercase(); let mut cipher_msg: String = msg.to_string(); let keys: Vec<&str> = if decrypt_mode { key_uppercase.split_whitespace().rev().collect() } else { key_uppercase.split_whitespace().collect() }; for cipher_key in keys.iter() { let mut key_order: Vec<usize> = Vec::new(); // Removes any non-alphabet characters from 'msg' cipher_msg = cipher_msg .to_uppercase() .chars() .filter(|&c| c.is_ascii_alphabetic()) .collect(); // Determines the sequence of the columns, as dictated by the // alphabetical order of the keyword's letters let mut key_ascii: Vec<(usize, u8)> = cipher_key.bytes().enumerate().collect::<Vec<(usize, u8)>>(); key_ascii.sort_by_key(|&(_, key)| key); for (counter, (_, key)) in key_ascii.iter_mut().enumerate() { *key = counter as u8; } key_ascii.sort_by_key(|&(index, _)| index); key_ascii .into_iter() .for_each(|(_, key)| key_order.push(key.into())); // Determines whether to encrypt or decrypt the message, // and returns the result cipher_msg = if decrypt_mode { decrypt(cipher_msg, key_order) } else { encrypt(cipher_msg, key_order) }; } cipher_msg } /// Performs the columnar transposition encryption fn encrypt(mut msg: String, key_order: Vec<usize>) -> String { let mut encrypted_msg: String = String::from(""); let mut encrypted_vec: Vec<String> = Vec::new(); let msg_len = msg.len(); let key_len: usize = key_order.len(); let mut msg_index: usize = msg_len; let mut key_index: usize = key_len; // Loop each column, pushing it to a Vec<T> while !msg.is_empty() { let mut chars: String = String::from(""); let mut index: usize = 0; key_index -= 1; // Loop every nth character, determined by key length, to create a column while index < msg_index { let ch = msg.remove(index); chars.push(ch); index += key_index; msg_index -= 1; } encrypted_vec.push(chars); } // Concatenate the columns into a string, determined by the // alphabetical order of the keyword's characters let mut indexed_vec: Vec<(usize, &String)> = Vec::new(); let mut indexed_msg: String = String::from(""); for (counter, key_index) in key_order.into_iter().enumerate() { indexed_vec.push((key_index, &encrypted_vec[counter])); } indexed_vec.sort(); for (_, column) in indexed_vec { indexed_msg.push_str(column); } // Split the message by a space every nth character, determined by // 'message length divided by keyword length' to the next highest integer. let msg_div: usize = (msg_len as f32 / key_len as f32).ceil() as usize; let mut counter: usize = 0; indexed_msg.chars().for_each(|c| { encrypted_msg.push(c); counter += 1; if counter == msg_div { encrypted_msg.push(' '); counter = 0; } }); encrypted_msg.trim_end().to_string() } /// Performs the columnar transposition decryption fn decrypt(mut msg: String, key_order: Vec<usize>) -> String { let mut decrypted_msg: String = String::from(""); let mut decrypted_vec: Vec<String> = Vec::new(); let mut indexed_vec: Vec<(usize, String)> = Vec::new(); let msg_len = msg.len(); let key_len: usize = key_order.len(); // Split the message into columns, determined by 'message length divided by keyword length'. // Some columns are larger by '+1', where the prior calculation leaves a remainder. let split_size: usize = (msg_len as f64 / key_len as f64) as usize; let msg_mod: usize = msg_len % key_len; let mut counter: usize = msg_mod; let mut key_split: Vec<usize> = key_order.clone(); let (split_large, split_small) = key_split.split_at_mut(msg_mod); split_large.sort_unstable(); split_small.sort_unstable(); split_large.iter_mut().rev().for_each(|key_index| { counter -= 1; let range: RangeInclusive<usize> = ((*key_index * split_size) + counter)..=(((*key_index + 1) * split_size) + counter); let slice: String = msg[range.clone()].to_string(); indexed_vec.push((*key_index, slice)); msg.replace_range(range, ""); }); for key_index in split_small.iter_mut() { let (slice, rest_of_msg) = msg.split_at(split_size); indexed_vec.push((*key_index, (slice.to_string()))); msg = rest_of_msg.to_string(); } indexed_vec.sort(); for key in key_order { if let Some((_, column)) = indexed_vec.iter().find(|(key_index, _)| key_index == &key) { decrypted_vec.push(column.to_string()); } } // Concatenate the columns into a string, determined by the // alphabetical order of the keyword's characters for _ in 0..split_size { decrypted_vec.iter_mut().for_each(|column| { decrypted_msg.push(column.remove(0)); }) } if !decrypted_vec.is_empty() { decrypted_vec.into_iter().for_each(|chars| { decrypted_msg.push_str(&chars); }) } decrypted_msg } #[cfg(test)] mod tests { use super::*; #[test] fn encryption() { assert_eq!( transposition( false, "The quick brown fox jumps over the lazy dog", "Archive", ), "TKOOL ERJEZ CFSEG QOURY UWMTD HBXVA INPHO" ); assert_eq!( transposition( false, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,/;'[]{}:|_+=-`~() ", "Tenacious" ), "DMVENW ENWFOX BKTCLU FOXGPY CLUDMV GPYHQZ IRAJSA JSBKTH QZIR" ); assert_eq!( transposition(false, "WE ARE DISCOVERED. FLEE AT ONCE.", "ZEBRAS"), "EVLNA CDTES EAROF ODEEC WIREE" ); } #[test] fn decryption() { assert_eq!( transposition(true, "TKOOL ERJEZ CFSEG QOURY UWMTD HBXVA INPHO", "Archive"), "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG" ); assert_eq!( transposition( true, "DMVENW ENWFOX BKTCLU FOXGPY CLUDMV GPYHQZ IRAJSA JSBKTH QZIR", "Tenacious" ), "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" ); assert_eq!( transposition(true, "EVLNA CDTES EAROF ODEEC WIREE", "ZEBRAS"), "WEAREDISCOVEREDFLEEATONCE" ); } #[test] fn double_encryption() { assert_eq!( transposition( false, "The quick brown fox jumps over the lazy dog", "Archive Snow" ), "KEZEUWHAH ORCGRMBIO TLESOUDVP OJFQYTXN" ); assert_eq!( transposition( false, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,/;'[]{}:|_+=-`~() ", "Tenacious Drink" ), "DWOCXLGZSKI VNBUPDYRJHN FTOCVQJBZEW KFYMHASQMEX LGUPIATR" ); assert_eq!( transposition(false, "WE ARE DISCOVERED. FLEE AT ONCE.", "ZEBRAS STRIPE"), "CAEEN SOIAE DRLEF WEDRE EVTOC" ); } #[test] fn double_decryption() { assert_eq!( transposition( true, "KEZEUWHAH ORCGRMBIO TLESOUDVP OJFQYTXN", "Archive Snow" ), "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG" ); assert_eq!( transposition( true, "DWOCXLGZSKI VNBUPDYRJHN FTOCVQJBZEW KFYMHASQMEX LGUPIATR", "Tenacious Drink", ), "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" ); assert_eq!( transposition(true, "CAEEN SOIAE DRLEF WEDRE EVTOC", "ZEBRAS STRIPE"), "WEAREDISCOVEREDFLEEATONCE" ); } }
{ "argument_definitions": [], "end_line": 206, "name": "blake2b", "signature": "pub fn blake2b(m: &[u8], k: &[u8], nn: u8) -> Vec<u8>", "start_line": 179 }
blake2b
pub fn blake2b(m: &[u8], k: &[u8], nn: u8) -> Vec<u8> { let kk = min(k.len(), KK_MAX); let nn = min(nn, NN_MAX); // Prevent user from giving a key that is too long let k = &k[..kk]; let dd = max(ceil(kk, BB) + ceil(m.len(), BB), 1); let mut blocks: Vec<Block> = vec![blank_block(); dd]; // Copy key into blocks for (w, c) in blocks[0].iter_mut().zip(k.chunks(U64BYTES)) { *w = bytes_to_word(c); } let first_index = (kk > 0) as usize; // Copy bytes from message into blocks for (i, c) in m.chunks(U64BYTES).enumerate() { let block_index = first_index + (i / (BB / U64BYTES)); let word_in_block = i % (BB / U64BYTES); blocks[block_index][word_in_block] = bytes_to_word(c); } blake2(blocks, m.len() as u128, kk as u64, nn as Word) }
Rust-master/src/ciphers/blake2b.rs
// For specification go to https://www.rfc-editor.org/rfc/rfc7693 use std::cmp::{max, min}; use std::convert::{TryFrom, TryInto}; type Word = u64; const BB: usize = 128; const U64BYTES: usize = (u64::BITS as usize) / 8; type Block = [Word; BB / U64BYTES]; const KK_MAX: usize = 64; const NN_MAX: u8 = 64; // Array of round constants used in mixing function G const RC: [u32; 4] = [32, 24, 16, 63]; // IV[i] = floor(2**64 * frac(sqrt(prime(i+1)))) where prime(i) is the ith prime number const IV: [Word; 8] = [ 0x6A09E667F3BCC908, 0xBB67AE8584CAA73B, 0x3C6EF372FE94F82B, 0xA54FF53A5F1D36F1, 0x510E527FADE682D1, 0x9B05688C2B3E6C1F, 0x1F83D9ABFB41BD6B, 0x5BE0CD19137E2179, ]; const SIGMA: [[usize; 16]; 10] = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8], [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9], [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11], [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10], [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5], [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0], ]; #[inline] const fn blank_block() -> Block { [0u64; BB / U64BYTES] } // Overflowing addition #[inline] fn add(a: &mut Word, b: Word) { *a = a.overflowing_add(b).0; } #[inline] const fn ceil(dividend: usize, divisor: usize) -> usize { (dividend / divisor) + ((dividend % divisor != 0) as usize) } fn g(v: &mut [Word; 16], a: usize, b: usize, c: usize, d: usize, x: Word, y: Word) { for (m, r) in [x, y].into_iter().zip(RC.chunks(2)) { let v_b = v[b]; add(&mut v[a], v_b); add(&mut v[a], m); v[d] = (v[d] ^ v[a]).rotate_right(r[0]); let v_d = v[d]; add(&mut v[c], v_d); v[b] = (v[b] ^ v[c]).rotate_right(r[1]); } } fn f(h: &mut [Word; 8], m: Block, t: u128, flag: bool) { let mut v: [Word; 16] = [0; 16]; for (i, (h_i, iv_i)) in h.iter().zip(IV.iter()).enumerate() { v[i] = *h_i; v[i + 8] = *iv_i; } v[12] ^= (t % (u64::MAX as u128)) as u64; v[13] ^= (t >> 64) as u64; if flag { v[14] = !v[14]; } for i in 0..12 { let s = SIGMA[i % 10]; let mut s_index = 0; for j in 0..4 { g( &mut v, j, j + 4, j + 8, j + 12, m[s[s_index]], m[s[s_index + 1]], ); s_index += 2; } let i1d = |col, row| { let col = col % 4; let row = row % 4; (row * 4) + col }; for j in 0..4 { // Produces indeces for diagonals of a 4x4 matrix starting at 0,j let idx: Vec<usize> = (0..4).map(|n| i1d(j + n, n) as usize).collect(); g( &mut v, idx[0], idx[1], idx[2], idx[3], m[s[s_index]], m[s[s_index + 1]], ); s_index += 2; } } for (i, n) in h.iter_mut().enumerate() { *n ^= v[i] ^ v[i + 8]; } } fn blake2(d: Vec<Block>, ll: u128, kk: Word, nn: Word) -> Vec<u8> { let mut h: [Word; 8] = IV .iter() .take(8) .copied() .collect::<Vec<Word>>() .try_into() .unwrap(); h[0] ^= 0x01010000u64 ^ (kk << 8) ^ nn; if d.len() > 1 { for (i, w) in d.iter().enumerate().take(d.len() - 1) { f(&mut h, *w, (i as u128 + 1) * BB as u128, false); } } let ll = if kk > 0 { ll + BB as u128 } else { ll }; f(&mut h, d[d.len() - 1], ll, true); h.iter() .flat_map(|n| n.to_le_bytes()) .take(nn as usize) .collect() } // Take arbitrarily long slice of u8's and turn up to 8 bytes into u64 fn bytes_to_word(bytes: &[u8]) -> Word { if let Ok(arr) = <[u8; U64BYTES]>::try_from(bytes) { Word::from_le_bytes(arr) } else { let mut arr = [0u8; 8]; for (a_i, b_i) in arr.iter_mut().zip(bytes) { *a_i = *b_i; } Word::from_le_bytes(arr) } } pub fn blake2b(m: &[u8], k: &[u8], nn: u8) -> Vec<u8> { let kk = min(k.len(), KK_MAX); let nn = min(nn, NN_MAX); // Prevent user from giving a key that is too long let k = &k[..kk]; let dd = max(ceil(kk, BB) + ceil(m.len(), BB), 1); let mut blocks: Vec<Block> = vec![blank_block(); dd]; // Copy key into blocks for (w, c) in blocks[0].iter_mut().zip(k.chunks(U64BYTES)) { *w = bytes_to_word(c); } let first_index = (kk > 0) as usize; // Copy bytes from message into blocks for (i, c) in m.chunks(U64BYTES).enumerate() { let block_index = first_index + (i / (BB / U64BYTES)); let word_in_block = i % (BB / U64BYTES); blocks[block_index][word_in_block] = bytes_to_word(c); } blake2(blocks, m.len() as u128, kk as u64, nn as Word) } #[cfg(test)] mod test { use super::*; macro_rules! digest_test { ($fname:ident, $message:expr, $key:expr, $nn:literal, $expected:expr) => { #[test] fn $fname() { let digest = blake2b($message, $key, $nn); let expected = Vec::from($expected); assert_eq!(digest, expected); } }; } digest_test!( blake2b_from_rfc, &[0x61, 0x62, 0x63], &[0; 0], 64, [ 0xBA, 0x80, 0xA5, 0x3F, 0x98, 0x1C, 0x4D, 0x0D, 0x6A, 0x27, 0x97, 0xB6, 0x9F, 0x12, 0xF6, 0xE9, 0x4C, 0x21, 0x2F, 0x14, 0x68, 0x5A, 0xC4, 0xB7, 0x4B, 0x12, 0xBB, 0x6F, 0xDB, 0xFF, 0xA2, 0xD1, 0x7D, 0x87, 0xC5, 0x39, 0x2A, 0xAB, 0x79, 0x2D, 0xC2, 0x52, 0xD5, 0xDE, 0x45, 0x33, 0xCC, 0x95, 0x18, 0xD3, 0x8A, 0xA8, 0xDB, 0xF1, 0x92, 0x5A, 0xB9, 0x23, 0x86, 0xED, 0xD4, 0x00, 0x99, 0x23 ] ); digest_test!( blake2b_empty, &[0; 0], &[0; 0], 64, [ 0x78, 0x6a, 0x02, 0xf7, 0x42, 0x01, 0x59, 0x03, 0xc6, 0xc6, 0xfd, 0x85, 0x25, 0x52, 0xd2, 0x72, 0x91, 0x2f, 0x47, 0x40, 0xe1, 0x58, 0x47, 0x61, 0x8a, 0x86, 0xe2, 0x17, 0xf7, 0x1f, 0x54, 0x19, 0xd2, 0x5e, 0x10, 0x31, 0xaf, 0xee, 0x58, 0x53, 0x13, 0x89, 0x64, 0x44, 0x93, 0x4e, 0xb0, 0x4b, 0x90, 0x3a, 0x68, 0x5b, 0x14, 0x48, 0xb7, 0x55, 0xd5, 0x6f, 0x70, 0x1a, 0xfe, 0x9b, 0xe2, 0xce ] ); digest_test!( blake2b_empty_with_key, &[0; 0], &[ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f ], 64, [ 0x10, 0xeb, 0xb6, 0x77, 0x00, 0xb1, 0x86, 0x8e, 0xfb, 0x44, 0x17, 0x98, 0x7a, 0xcf, 0x46, 0x90, 0xae, 0x9d, 0x97, 0x2f, 0xb7, 0xa5, 0x90, 0xc2, 0xf0, 0x28, 0x71, 0x79, 0x9a, 0xaa, 0x47, 0x86, 0xb5, 0xe9, 0x96, 0xe8, 0xf0, 0xf4, 0xeb, 0x98, 0x1f, 0xc2, 0x14, 0xb0, 0x05, 0xf4, 0x2d, 0x2f, 0xf4, 0x23, 0x34, 0x99, 0x39, 0x16, 0x53, 0xdf, 0x7a, 0xef, 0xcb, 0xc1, 0x3f, 0xc5, 0x15, 0x68 ] ); digest_test!( blake2b_key_shortin, &[0], &[ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f ], 64, [ 0x96, 0x1f, 0x6d, 0xd1, 0xe4, 0xdd, 0x30, 0xf6, 0x39, 0x01, 0x69, 0x0c, 0x51, 0x2e, 0x78, 0xe4, 0xb4, 0x5e, 0x47, 0x42, 0xed, 0x19, 0x7c, 0x3c, 0x5e, 0x45, 0xc5, 0x49, 0xfd, 0x25, 0xf2, 0xe4, 0x18, 0x7b, 0x0b, 0xc9, 0xfe, 0x30, 0x49, 0x2b, 0x16, 0xb0, 0xd0, 0xbc, 0x4e, 0xf9, 0xb0, 0xf3, 0x4c, 0x70, 0x03, 0xfa, 0xc0, 0x9a, 0x5e, 0xf1, 0x53, 0x2e, 0x69, 0x43, 0x02, 0x34, 0xce, 0xbd ] ); digest_test!( blake2b_keyed_filled, &[ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f ], &[ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f ], 64, [ 0x65, 0x67, 0x6d, 0x80, 0x06, 0x17, 0x97, 0x2f, 0xbd, 0x87, 0xe4, 0xb9, 0x51, 0x4e, 0x1c, 0x67, 0x40, 0x2b, 0x7a, 0x33, 0x10, 0x96, 0xd3, 0xbf, 0xac, 0x22, 0xf1, 0xab, 0xb9, 0x53, 0x74, 0xab, 0xc9, 0x42, 0xf1, 0x6e, 0x9a, 0xb0, 0xea, 0xd3, 0x3b, 0x87, 0xc9, 0x19, 0x68, 0xa6, 0xe5, 0x09, 0xe1, 0x19, 0xff, 0x07, 0x78, 0x7b, 0x3e, 0xf4, 0x83, 0xe1, 0xdc, 0xdc, 0xcf, 0x6e, 0x30, 0x22 ] ); }
{ "argument_definitions": [], "end_line": 21, "name": "decimal_to_hexadecimal", "signature": "pub fn decimal_to_hexadecimal(base_num: u64) -> String", "start_line": 1 }
decimal_to_hexadecimal
pub fn decimal_to_hexadecimal(base_num: u64) -> String { let mut num = base_num; let mut hexadecimal_num = String::new(); loop { let remainder = num % 16; let hex_char = if remainder < 10 { (remainder as u8 + b'0') as char } else { (remainder as u8 - 10 + b'A') as char }; hexadecimal_num.insert(0, hex_char); num /= 16; if num == 0 { break; } } hexadecimal_num }
Rust-master/src/conversions/decimal_to_hexadecimal.rs
pub fn decimal_to_hexadecimal(base_num: u64) -> String { let mut num = base_num; let mut hexadecimal_num = String::new(); loop { let remainder = num % 16; let hex_char = if remainder < 10 { (remainder as u8 + b'0') as char } else { (remainder as u8 - 10 + b'A') as char }; hexadecimal_num.insert(0, hex_char); num /= 16; if num == 0 { break; } } hexadecimal_num } #[cfg(test)] mod tests { use super::*; #[test] fn test_zero() { assert_eq!(decimal_to_hexadecimal(0), "0"); } #[test] fn test_single_digit_decimal() { assert_eq!(decimal_to_hexadecimal(9), "9"); } #[test] fn test_single_digit_hexadecimal() { assert_eq!(decimal_to_hexadecimal(12), "C"); } #[test] fn test_multiple_digit_hexadecimal() { assert_eq!(decimal_to_hexadecimal(255), "FF"); } #[test] fn test_big() { assert_eq!(decimal_to_hexadecimal(u64::MAX), "FFFFFFFFFFFFFFFF"); } #[test] fn test_random() { assert_eq!(decimal_to_hexadecimal(123456), "1E240"); } }
{ "argument_definitions": [ { "definitions": [ "pub fn area_under_curve(start: f64, end: f64, func: fn(f64) -> f64, step_count: usize) -> f64 {\n assert!(step_count > 0);\n\n let (start, end) = if start > end {\n (end, start)\n } else {\n (start, end)\n }; //swap if bounds reversed\n\n let step_length: f64 = (end - start) / step_count as f64;\n let mut area = 0f64;\n let mut fx1 = func(start);\n let mut fx2: f64;\n\n for eval_point in (1..=step_count).map(|x| (x as f64 * step_length) + start) {\n fx2 = func(eval_point);\n area += (fx2 + fx1).abs() * step_length * 0.5;\n fx1 = fx2;\n }\n\n area\n}" ], "name": "func", "type": "fn(f64" } ], "end_line": 22, "name": "area_under_curve", "signature": "pub fn area_under_curve(start: f64, end: f64, func: fn(f64) -> f64, step_count: usize) -> f64", "start_line": 1 }
area_under_curve
pub fn area_under_curve(start: f64, end: f64, func: fn(f64) -> f64, step_count: usize) -> f64 { assert!(step_count > 0); let (start, end) = if start > end { (end, start) } else { (start, end) }; //swap if bounds reversed let step_length: f64 = (end - start) / step_count as f64; let mut area = 0f64; let mut fx1 = func(start); let mut fx2: f64; for eval_point in (1..=step_count).map(|x| (x as f64 * step_length) + start) { fx2 = func(eval_point); area += (fx2 + fx1).abs() * step_length * 0.5; fx1 = fx2; } area }
Rust-master/src/math/area_under_curve.rs
pub fn area_under_curve(start: f64, end: f64, func: fn(f64) -> f64, step_count: usize) -> f64 { assert!(step_count > 0); let (start, end) = if start > end { (end, start) } else { (start, end) }; //swap if bounds reversed let step_length: f64 = (end - start) / step_count as f64; let mut area = 0f64; let mut fx1 = func(start); let mut fx2: f64; for eval_point in (1..=step_count).map(|x| (x as f64 * step_length) + start) { fx2 = func(eval_point); area += (fx2 + fx1).abs() * step_length * 0.5; fx1 = fx2; } area } #[cfg(test)] mod test { use super::*; #[test] fn test_linear_func() { assert_eq!(area_under_curve(1f64, 2f64, |x| x, 10), 1.5000000000000002); } #[test] fn test_quadratic_func() { assert_eq!( area_under_curve(1f64, 2f64, |x| x * x, 1000), 2.333333500000005 ); } #[test] fn test_zero_length() { assert_eq!(area_under_curve(0f64, 0f64, |x| x * x, 1000), 0.0); } #[test] fn test_reverse() { assert_eq!( area_under_curve(1f64, 2f64, |x| x, 10), area_under_curve(2f64, 1f64, |x| x, 10) ); } }
{ "argument_definitions": [], "end_line": 65, "name": "miller_rabin", "signature": "pub fn miller_rabin(number: u64, bases: &[u64]) -> u64", "start_line": 38 }
miller_rabin
pub fn miller_rabin(number: u64, bases: &[u64]) -> u64 { // returns zero on a probable prime, and a witness if number is not prime // A base set for deterministic performance on 64 bit numbers is: // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] // another one for 32 bits: // [2, 3, 5, 7], with smallest number to fail 3'215'031'751 = 151 * 751 * 28351 // note that all bases should be prime if number <= 4 { match number { 0 => { panic!("0 is invalid input for Miller-Rabin. 0 is not prime by definition, but has no witness"); } 2 | 3 => return 0, _ => return number, } } if bases.contains(&number) { return 0; } let two_power: u64 = (number - 1).trailing_zeros() as u64; let odd_power = (number - 1) >> two_power; for base in bases { if !check_prime_base(number, *base, two_power, odd_power) { return *base; } } 0 }
Rust-master/src/math/miller_rabin.rs
use num_bigint::BigUint; use num_traits::{One, ToPrimitive, Zero}; use std::cmp::Ordering; fn modulo_power(mut base: u64, mut power: u64, modulo: u64) -> u64 { base %= modulo; if base == 0 { return 0; // return zero if base is divisible by modulo } let mut ans: u128 = 1; let mut bbase: u128 = base as u128; while power > 0 { if (power % 2) == 1 { ans = (ans * bbase) % (modulo as u128); } bbase = (bbase * bbase) % (modulo as u128); power /= 2; } ans as u64 } fn check_prime_base(number: u64, base: u64, two_power: u64, odd_power: u64) -> bool { // returns false if base is a witness let mut x: u128 = modulo_power(base, odd_power, number) as u128; let bnumber: u128 = number as u128; if x == 1 || x == (bnumber - 1) { return true; } for _ in 1..two_power { x = (x * x) % bnumber; if x == (bnumber - 1) { return true; } } false } pub fn miller_rabin(number: u64, bases: &[u64]) -> u64 { // returns zero on a probable prime, and a witness if number is not prime // A base set for deterministic performance on 64 bit numbers is: // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] // another one for 32 bits: // [2, 3, 5, 7], with smallest number to fail 3'215'031'751 = 151 * 751 * 28351 // note that all bases should be prime if number <= 4 { match number { 0 => { panic!("0 is invalid input for Miller-Rabin. 0 is not prime by definition, but has no witness"); } 2 | 3 => return 0, _ => return number, } } if bases.contains(&number) { return 0; } let two_power: u64 = (number - 1).trailing_zeros() as u64; let odd_power = (number - 1) >> two_power; for base in bases { if !check_prime_base(number, *base, two_power, odd_power) { return *base; } } 0 } pub fn big_miller_rabin(number_ref: &BigUint, bases: &[u64]) -> u64 { let number = number_ref.clone(); if BigUint::from(5u32).cmp(&number) == Ordering::Greater { if number.eq(&BigUint::zero()) { panic!("0 is invalid input for Miller-Rabin. 0 is not prime by definition, but has no witness"); } else if number.eq(&BigUint::from(2u32)) || number.eq(&BigUint::from(3u32)) { return 0; } else { return number.to_u64().unwrap(); } } if let Some(num) = number.to_u64() { if bases.contains(&num) { return 0; } } let num_minus_one = &number - BigUint::one(); let two_power: u64 = num_minus_one.trailing_zeros().unwrap(); let odd_power: BigUint = &num_minus_one >> two_power; for base in bases { let mut x = BigUint::from(*base).modpow(&odd_power, &number); if x.eq(&BigUint::one()) || x.eq(&num_minus_one) { continue; } let mut not_a_witness = false; for _ in 1..two_power { x = (&x * &x) % &number; if x.eq(&num_minus_one) { not_a_witness = true; break; } } if not_a_witness { continue; } return *base; } 0 } #[cfg(test)] mod tests { use super::*; static DEFAULT_BASES: [u64; 12] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]; #[test] fn basic() { // these bases make miller rabin deterministic for any number < 2 ^ 64 // can use smaller number of bases for deterministic performance for numbers < 2 ^ 32 assert_eq!(miller_rabin(3, &DEFAULT_BASES), 0); assert_eq!(miller_rabin(7, &DEFAULT_BASES), 0); assert_eq!(miller_rabin(11, &DEFAULT_BASES), 0); assert_eq!(miller_rabin(2003, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(1, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(4, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(6, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(21, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(2004, &DEFAULT_BASES), 0); // bigger test cases. // primes are generated using openssl // non primes are randomly picked and checked using openssl // primes: assert_eq!(miller_rabin(3629611793, &DEFAULT_BASES), 0); assert_eq!(miller_rabin(871594686869, &DEFAULT_BASES), 0); assert_eq!(miller_rabin(968236663804121, &DEFAULT_BASES), 0); assert_eq!(miller_rabin(6920153791723773023, &DEFAULT_BASES), 0); // random non primes: assert_ne!(miller_rabin(4546167556336341257, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(4363186415423517377, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(815479701131020226, &DEFAULT_BASES), 0); // these two are made of two 31 bit prime factors: // 1950202127 * 2058609037 = 4014703722618821699 assert_ne!(miller_rabin(4014703722618821699, &DEFAULT_BASES), 0); // 1679076769 * 2076341633 = 3486337000477823777 assert_ne!(miller_rabin(3486337000477823777, &DEFAULT_BASES), 0); } #[test] fn big_basic() { assert_eq!(big_miller_rabin(&BigUint::from(3u32), &DEFAULT_BASES), 0); assert_eq!(big_miller_rabin(&BigUint::from(7u32), &DEFAULT_BASES), 0); assert_eq!(big_miller_rabin(&BigUint::from(11u32), &DEFAULT_BASES), 0); assert_eq!(big_miller_rabin(&BigUint::from(2003u32), &DEFAULT_BASES), 0); assert_ne!(big_miller_rabin(&BigUint::from(1u32), &DEFAULT_BASES), 0); assert_ne!(big_miller_rabin(&BigUint::from(4u32), &DEFAULT_BASES), 0); assert_ne!(big_miller_rabin(&BigUint::from(6u32), &DEFAULT_BASES), 0); assert_ne!(big_miller_rabin(&BigUint::from(21u32), &DEFAULT_BASES), 0); assert_ne!(big_miller_rabin(&BigUint::from(2004u32), &DEFAULT_BASES), 0); assert_eq!( big_miller_rabin(&BigUint::from(3629611793u64), &DEFAULT_BASES), 0 ); assert_eq!( big_miller_rabin(&BigUint::from(871594686869u64), &DEFAULT_BASES), 0 ); assert_eq!( big_miller_rabin(&BigUint::from(968236663804121u64), &DEFAULT_BASES), 0 ); assert_eq!( big_miller_rabin(&BigUint::from(6920153791723773023u64), &DEFAULT_BASES), 0 ); assert_ne!( big_miller_rabin(&BigUint::from(4546167556336341257u64), &DEFAULT_BASES), 0 ); assert_ne!( big_miller_rabin(&BigUint::from(4363186415423517377u64), &DEFAULT_BASES), 0 ); assert_ne!( big_miller_rabin(&BigUint::from(815479701131020226u64), &DEFAULT_BASES), 0 ); assert_ne!( big_miller_rabin(&BigUint::from(4014703722618821699u64), &DEFAULT_BASES), 0 ); assert_ne!( big_miller_rabin(&BigUint::from(3486337000477823777u64), &DEFAULT_BASES), 0 ); } #[test] #[ignore] fn big_primes() { let p1 = BigUint::parse_bytes(b"4764862697132131451620315518348229845593592794669", 10).unwrap(); assert_eq!(big_miller_rabin(&p1, &DEFAULT_BASES), 0); let p2 = BigUint::parse_bytes( b"12550757946601963214089118080443488976766669415957018428703", 10, ) .unwrap(); assert_eq!(big_miller_rabin(&p2, &DEFAULT_BASES), 0); // An RSA-worthy prime let p3 = BigUint::parse_bytes(b"157d6l5zkv45ve4azfw7nyyjt6rzir2gcjoytjev5iacnkaii8hlkyk3op7bx9qfqiie23vj9iw4qbp7zupydfq9ut6mq6m36etya6cshtqi1yi9q5xyiws92el79dqt8qk7l2pqmxaa0sxhmd2vpaibo9dkfd029j1rvkwlw4724ctgaqs5jzy0bqi5pqdjc2xerhn", 36).unwrap(); assert_eq!(big_miller_rabin(&p3, &DEFAULT_BASES), 0); let n1 = BigUint::parse_bytes(b"coy6tkiaqswmce1r03ycdif3t796wzjwneewbe3cmncaplm85jxzcpdmvy0moic3lql70a81t5qdn2apac0dndhohewkspuk1wyndxsgxs3ux4a7730unru7dfmygh", 36).unwrap(); assert_ne!(big_miller_rabin(&n1, &DEFAULT_BASES), 0); // RSA-2048 let n2 = BigUint::parse_bytes(b"4l91lq4a2sgekpv8ukx1gxsk7mfeks46haggorlkazm0oufxwijid6q6v44u5me3kz3ne6yczp4fcvo62oej72oe7pjjtyxgid5b8xdz1e8daafspbzcy1hd8i4urjh9hm0tyylsgqsss3jn372d6fmykpw4bb9cr1ngxnncsbod3kg49o7owzqnsci5pwqt8bch0t60gq0st2gyx7ii3mzhb1pp1yvjyor35hwvok1sxj3ih46rpd27li8y5yli3mgdttcn65k3szfa6rbcnbgkojqjjq72gar6raslnh6sjd2fy7yj3bwo43obvbg3ws8y28kpol3okb5b3fld03sq1kgrj2fugiaxgplva6x5ssilqq4g0b21xy2kiou3sqsgonmqx55v", 36).unwrap(); assert_ne!(big_miller_rabin(&n2, &DEFAULT_BASES), 0); } }
{ "argument_definitions": [], "end_line": 101, "name": "bell_number", "signature": "pub fn bell_number(n: u32) -> BigUint", "start_line": 69 }
bell_number
pub fn bell_number(n: u32) -> BigUint { let needs_resize; // Check if number is already in lookup table { let lookup_table = LOOKUP_TABLE_LOCK.read().unwrap(); if let Some(entry) = lookup_table.get(n as usize) { return entry; } needs_resize = (n + 1) as usize > lookup_table.capacity(); } // Resize table before recursion so that if more values need to be added during recursion the table isn't // reallocated every single time if needs_resize { let mut lookup_table = LOOKUP_TABLE_LOCK.write().unwrap(); lookup_table.resize((n + 1) as usize); } let new_bell_number: BigUint = (0..n).map(|x| bell_number(x) * n_choose_r(n - 1, x)).sum(); // Add new number to lookup table { let mut lookup_table = LOOKUP_TABLE_LOCK.write().unwrap(); lookup_table.set(n as usize, new_bell_number.clone()); } new_bell_number }
Rust-master/src/math/bell_numbers.rs
use num_bigint::BigUint; use num_traits::{One, Zero}; use std::sync::RwLock; /// Returns the number of ways you can select r items given n options fn n_choose_r(n: u32, r: u32) -> BigUint { if r == n || r == 0 { return One::one(); } if r > n { return Zero::zero(); } // Any combination will only need to be computed once, thus giving no need to // memoize this function let product: BigUint = (0..r).fold(BigUint::one(), |acc, x| { (acc * BigUint::from(n - x)) / BigUint::from(x + 1) }); product } /// A memoization table for storing previous results struct MemTable { buffer: Vec<BigUint>, } impl MemTable { const fn new() -> Self { MemTable { buffer: Vec::new() } } fn get(&self, n: usize) -> Option<BigUint> { if n == 0 || n == 1 { Some(BigUint::one()) } else if let Some(entry) = self.buffer.get(n) { if *entry == BigUint::zero() { None } else { Some(entry.clone()) } } else { None } } fn set(&mut self, n: usize, b: BigUint) { self.buffer[n] = b; } #[inline] fn capacity(&self) -> usize { self.buffer.capacity() } #[inline] fn resize(&mut self, new_size: usize) { if new_size > self.buffer.len() { self.buffer.resize(new_size, Zero::zero()); } } } // Implemented with RwLock so it is accessible across threads static LOOKUP_TABLE_LOCK: RwLock<MemTable> = RwLock::new(MemTable::new()); pub fn bell_number(n: u32) -> BigUint { let needs_resize; // Check if number is already in lookup table { let lookup_table = LOOKUP_TABLE_LOCK.read().unwrap(); if let Some(entry) = lookup_table.get(n as usize) { return entry; } needs_resize = (n + 1) as usize > lookup_table.capacity(); } // Resize table before recursion so that if more values need to be added during recursion the table isn't // reallocated every single time if needs_resize { let mut lookup_table = LOOKUP_TABLE_LOCK.write().unwrap(); lookup_table.resize((n + 1) as usize); } let new_bell_number: BigUint = (0..n).map(|x| bell_number(x) * n_choose_r(n - 1, x)).sum(); // Add new number to lookup table { let mut lookup_table = LOOKUP_TABLE_LOCK.write().unwrap(); lookup_table.set(n as usize, new_bell_number.clone()); } new_bell_number } #[cfg(test)] pub mod tests { use super::*; use std::str::FromStr; #[test] fn test_choose_zero() { for i in 1..100 { assert_eq!(n_choose_r(i, 0), One::one()); } } #[test] fn test_combination() { let five_choose_1 = BigUint::from(5u32); assert_eq!(n_choose_r(5, 1), five_choose_1); assert_eq!(n_choose_r(5, 4), five_choose_1); let ten_choose_3 = BigUint::from(120u32); assert_eq!(n_choose_r(10, 3), ten_choose_3); assert_eq!(n_choose_r(10, 7), ten_choose_3); let fourty_two_choose_thirty = BigUint::from_str("11058116888").unwrap(); assert_eq!(n_choose_r(42, 30), fourty_two_choose_thirty); assert_eq!(n_choose_r(42, 12), fourty_two_choose_thirty); } #[test] fn test_bell_numbers() { let bell_one = BigUint::from(1u32); assert_eq!(bell_number(1), bell_one); let bell_three = BigUint::from(5u32); assert_eq!(bell_number(3), bell_three); let bell_eight = BigUint::from(4140u32); assert_eq!(bell_number(8), bell_eight); let bell_six = BigUint::from(203u32); assert_eq!(bell_number(6), bell_six); let bell_twenty_six = BigUint::from_str("49631246523618756274").unwrap(); assert_eq!(bell_number(26), bell_twenty_six); } }
{ "argument_definitions": [], "end_line": 56, "name": "least_square_approx", "signature": "pub fn least_square_approx(\n points: &[(T, U)],\n degree: i32,\n) -> Option<Vec<f64>>", "start_line": 12 }
least_square_approx
pub fn least_square_approx( points: &[(T, U)], degree: i32, ) -> Option<Vec<f64>> { use nalgebra::{DMatrix, DVector}; /* Used for rounding floating numbers */ fn round_to_decimals(value: f64, decimals: i32) -> f64 { let multiplier = 10f64.powi(decimals); (value * multiplier).round() / multiplier } /* Casting the data parsed to this function to f64 (as some points can have decimals) */ let vals: Vec<(f64, f64)> = points .iter() .map(|(x, y)| ((*x).into(), (*y).into())) .collect(); /* Because of collect we need the Copy Trait for T and U */ /* Computes the sums in the system of equations */ let mut sums = Vec::<f64>::new(); for i in 1..=(2 * degree + 1) { sums.push(vals.iter().map(|(x, _)| x.powi(i - 1)).sum()); } /* Compute the free terms column vector */ let mut free_col = Vec::<f64>::new(); for i in 1..=(degree + 1) { free_col.push(vals.iter().map(|(x, y)| y * (x.powi(i - 1))).sum()); } let b = DVector::from_row_slice(&free_col); /* Create and fill the system's matrix */ let size = (degree + 1) as usize; let a = DMatrix::from_fn(size, size, |i, j| sums[degree as usize + i - j]); /* Solve the system of equations: A * x = b */ match a.qr().solve(&b) { Some(x) => { let rez: Vec<f64> = x.iter().map(|x| round_to_decimals(*x, 5)).collect(); Some(rez) } None => None, //<-- The system cannot be solved (badly conditioned system's matrix) } }
Rust-master/src/math/least_square_approx.rs
/// Least Square Approximation <p> /// Function that returns a polynomial which very closely passes through the given points (in 2D) /// /// The result is made of coeficients, in descending order (from x^degree to free term) /// /// Parameters: /// /// points -> coordinates of given points /// /// degree -> degree of the polynomial /// pub fn least_square_approx<T: Into<f64> + Copy, U: Into<f64> + Copy>( points: &[(T, U)], degree: i32, ) -> Option<Vec<f64>> { use nalgebra::{DMatrix, DVector}; /* Used for rounding floating numbers */ fn round_to_decimals(value: f64, decimals: i32) -> f64 { let multiplier = 10f64.powi(decimals); (value * multiplier).round() / multiplier } /* Casting the data parsed to this function to f64 (as some points can have decimals) */ let vals: Vec<(f64, f64)> = points .iter() .map(|(x, y)| ((*x).into(), (*y).into())) .collect(); /* Because of collect we need the Copy Trait for T and U */ /* Computes the sums in the system of equations */ let mut sums = Vec::<f64>::new(); for i in 1..=(2 * degree + 1) { sums.push(vals.iter().map(|(x, _)| x.powi(i - 1)).sum()); } /* Compute the free terms column vector */ let mut free_col = Vec::<f64>::new(); for i in 1..=(degree + 1) { free_col.push(vals.iter().map(|(x, y)| y * (x.powi(i - 1))).sum()); } let b = DVector::from_row_slice(&free_col); /* Create and fill the system's matrix */ let size = (degree + 1) as usize; let a = DMatrix::from_fn(size, size, |i, j| sums[degree as usize + i - j]); /* Solve the system of equations: A * x = b */ match a.qr().solve(&b) { Some(x) => { let rez: Vec<f64> = x.iter().map(|x| round_to_decimals(*x, 5)).collect(); Some(rez) } None => None, //<-- The system cannot be solved (badly conditioned system's matrix) } } #[cfg(test)] mod tests { use super::*; #[test] fn ten_points_1st_degree() { let points = vec![ (5.3, 7.8), (4.9, 8.1), (6.1, 6.9), (4.7, 8.3), (6.5, 7.7), (5.6, 7.0), (5.8, 8.2), (4.5, 8.0), (6.3, 7.2), (5.1, 8.4), ]; assert_eq!( least_square_approx(&points, 1), Some(vec![-0.49069, 10.44898]) ); } #[test] fn eight_points_5th_degree() { let points = vec![ (4f64, 8f64), (8f64, 2f64), (1f64, 7f64), (10f64, 3f64), (11.0, 0.0), (7.0, 3.0), (10.0, 1.0), (13.0, 13.0), ]; assert_eq!( least_square_approx(&points, 5), Some(vec![ 0.00603, -0.21304, 2.79929, -16.53468, 40.29473, -19.35771 ]) ); } #[test] fn four_points_2nd_degree() { let points = vec![ (2.312, 8.345344), (-2.312, 8.345344), (-0.7051, 3.49716601), (0.7051, 3.49716601), ]; assert_eq!(least_square_approx(&points, 2), Some(vec![1.0, 0.0, 3.0])); } }
{ "argument_definitions": [], "end_line": 84, "name": "modular_exponential", "signature": "pub fn modular_exponential(base: i64, mut power: i64, modulus: i64) -> i64", "start_line": 60 }
modular_exponential
pub fn modular_exponential(base: i64, mut power: i64, modulus: i64) -> i64 { if modulus == 1 { return 0; // Base case: any number modulo 1 is 0 } // Adjust if the exponent is negative by finding the modular inverse let mut base = if power < 0 { mod_inverse(base, modulus) } else { base % modulus }; let mut result = 1; // Initialize result power = power.abs(); // Work with the absolute value of the exponent // Perform the exponentiation while power > 0 { if power & 1 == 1 { result = (result * base) % modulus; } power >>= 1; // Divide the power by 2 base = (base * base) % modulus; // Square the base } result }
Rust-master/src/math/modular_exponential.rs
/// Calculate the greatest common divisor (GCD) of two numbers and the /// coefficients of BΓ©zout's identity using the Extended Euclidean Algorithm. /// /// # Arguments /// /// * `a` - One of the numbers to find the GCD of /// * `m` - The other number to find the GCD of /// /// # Returns /// /// A tuple (gcd, x1, x2) such that: /// gcd - the greatest common divisor of a and m. /// x1, x2 - the coefficients such that `a * x1 + m * x2` is equivalent to `gcd` modulo `m`. pub fn gcd_extended(a: i64, m: i64) -> (i64, i64, i64) { if a == 0 { (m, 0, 1) } else { let (gcd, x1, x2) = gcd_extended(m % a, a); let x = x2 - (m / a) * x1; (gcd, x, x1) } } /// Find the modular multiplicative inverse of a number modulo `m`. /// /// # Arguments /// /// * `b` - The number to find the modular inverse of /// * `m` - The modulus /// /// # Returns /// /// The modular inverse of `b` modulo `m`. /// /// # Panics /// /// Panics if the inverse does not exist (i.e., `b` and `m` are not coprime). pub fn mod_inverse(b: i64, m: i64) -> i64 { let (gcd, x, _) = gcd_extended(b, m); if gcd != 1 { panic!("Inverse does not exist"); } else { // Ensure the modular inverse is positive (x % m + m) % m } } /// Perform modular exponentiation of a number raised to a power modulo `m`. /// This function handles both positive and negative exponents. /// /// # Arguments /// /// * `base` - The base number to be raised to the `power` /// * `power` - The exponent to raise the `base` to /// * `modulus` - The modulus to perform the operation under /// /// # Returns /// /// The result of `base` raised to `power` modulo `modulus`. pub fn modular_exponential(base: i64, mut power: i64, modulus: i64) -> i64 { if modulus == 1 { return 0; // Base case: any number modulo 1 is 0 } // Adjust if the exponent is negative by finding the modular inverse let mut base = if power < 0 { mod_inverse(base, modulus) } else { base % modulus }; let mut result = 1; // Initialize result power = power.abs(); // Work with the absolute value of the exponent // Perform the exponentiation while power > 0 { if power & 1 == 1 { result = (result * base) % modulus; } power >>= 1; // Divide the power by 2 base = (base * base) % modulus; // Square the base } result } #[cfg(test)] mod tests { use super::*; #[test] fn test_modular_exponential_positive() { assert_eq!(modular_exponential(2, 3, 5), 3); // 2^3 % 5 = 8 % 5 = 3 assert_eq!(modular_exponential(7, 2, 13), 10); // 7^2 % 13 = 49 % 13 = 10 assert_eq!(modular_exponential(5, 5, 31), 25); // 5^5 % 31 = 3125 % 31 = 25 assert_eq!(modular_exponential(10, 8, 11), 1); // 10^8 % 11 = 100000000 % 11 = 1 assert_eq!(modular_exponential(123, 45, 67), 62); // 123^45 % 67 } #[test] fn test_modular_inverse() { assert_eq!(mod_inverse(7, 13), 2); // Inverse of 7 mod 13 is 2 assert_eq!(mod_inverse(5, 31), 25); // Inverse of 5 mod 31 is 25 assert_eq!(mod_inverse(10, 11), 10); // Inverse of 10 mod 1 is 10 assert_eq!(mod_inverse(123, 67), 6); // Inverse of 123 mod 67 is 6 assert_eq!(mod_inverse(9, 17), 2); // Inverse of 9 mod 17 is 2 } #[test] fn test_modular_exponential_negative() { assert_eq!( modular_exponential(7, -2, 13), mod_inverse(7, 13).pow(2) % 13 ); // Inverse of 7 mod 13 is 2, 2^2 % 13 = 4 % 13 = 4 assert_eq!( modular_exponential(5, -5, 31), mod_inverse(5, 31).pow(5) % 31 ); // Inverse of 5 mod 31 is 25, 25^5 % 31 = 25 assert_eq!( modular_exponential(10, -8, 11), mod_inverse(10, 11).pow(8) % 11 ); // Inverse of 10 mod 11 is 10, 10^8 % 11 = 10 assert_eq!( modular_exponential(123, -5, 67), mod_inverse(123, 67).pow(5) % 67 ); // Inverse of 123 mod 67 is calculated via the function } #[test] fn test_modular_exponential_edge_cases() { assert_eq!(modular_exponential(0, 0, 1), 0); // 0^0 % 1 should be 0 as the modulus is 1 assert_eq!(modular_exponential(0, 10, 1), 0); // 0^n % 1 should be 0 for any n assert_eq!(modular_exponential(10, 0, 1), 0); // n^0 % 1 should be 0 for any n assert_eq!(modular_exponential(1, 1, 1), 0); // 1^1 % 1 should be 0 assert_eq!(modular_exponential(-1, 2, 1), 0); // (-1)^2 % 1 should be 0 } }
{ "argument_definitions": [], "end_line": 22, "name": "prime_factors", "signature": "pub fn prime_factors(n: u64) -> Vec<u64>", "start_line": 3 }
prime_factors
pub fn prime_factors(n: u64) -> Vec<u64> { let mut i = 2; let mut n = n; let mut factors = Vec::new(); while i * i <= n { if n % i != 0 { if i != 2 { i += 1; } i += 1; } else { n /= i; factors.push(i); } } if n > 1 { factors.push(n); } factors }
Rust-master/src/math/prime_factors.rs
// Finds the prime factors of a number in increasing order, with repetition. pub fn prime_factors(n: u64) -> Vec<u64> { let mut i = 2; let mut n = n; let mut factors = Vec::new(); while i * i <= n { if n % i != 0 { if i != 2 { i += 1; } i += 1; } else { n /= i; factors.push(i); } } if n > 1 { factors.push(n); } factors } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { assert_eq!(prime_factors(0), vec![]); assert_eq!(prime_factors(1), vec![]); assert_eq!(prime_factors(11), vec![11]); assert_eq!(prime_factors(25), vec![5, 5]); assert_eq!(prime_factors(33), vec![3, 11]); assert_eq!(prime_factors(2560), vec![2, 2, 2, 2, 2, 2, 2, 2, 2, 5]); } }
{ "argument_definitions": [], "end_line": 35, "name": "baby_step_giant_step", "signature": "pub fn baby_step_giant_step(a: usize, b: usize, n: usize) -> Option<usize>", "start_line": 13 }
baby_step_giant_step
pub fn baby_step_giant_step(a: usize, b: usize, n: usize) -> Option<usize> { if greatest_common_divisor::greatest_common_divisor_stein(a as u64, n as u64) != 1 { return None; } let mut h_map = HashMap::new(); let m = (n as f64).sqrt().ceil() as usize; // baby step let mut step = 1; for i in 0..m { h_map.insert((step * b) % n, i); step = (step * a) % n; } // Now step = a^m (mod n), giant step let giant_step = step; for i in (m..=n).step_by(m) { if let Some(v) = h_map.get(&step) { return Some(i - v); } step = (step * giant_step) % n; } None }
Rust-master/src/math/baby_step_giant_step.rs
use crate::math::greatest_common_divisor; /// Baby-step Giant-step algorithm /// /// Solving discrete logarithm problem: /// a^x = b (mod n) , with respect to gcd(a, n) == 1 /// with O(sqrt(n)) time complexity. /// /// Wikipedia reference: https://en.wikipedia.org/wiki/Baby-step_giant-step /// When a is the primitive root modulo n, the answer is unique. /// Otherwise it will return the smallest positive solution use std::collections::HashMap; pub fn baby_step_giant_step(a: usize, b: usize, n: usize) -> Option<usize> { if greatest_common_divisor::greatest_common_divisor_stein(a as u64, n as u64) != 1 { return None; } let mut h_map = HashMap::new(); let m = (n as f64).sqrt().ceil() as usize; // baby step let mut step = 1; for i in 0..m { h_map.insert((step * b) % n, i); step = (step * a) % n; } // Now step = a^m (mod n), giant step let giant_step = step; for i in (m..=n).step_by(m) { if let Some(v) = h_map.get(&step) { return Some(i - v); } step = (step * giant_step) % n; } None } #[cfg(test)] mod tests { use super::baby_step_giant_step; #[test] fn small_numbers() { assert_eq!(baby_step_giant_step(5, 3, 11), Some(2)); assert_eq!(baby_step_giant_step(3, 83, 100), Some(9)); assert_eq!(baby_step_giant_step(9, 1, 61), Some(5)); assert_eq!(baby_step_giant_step(5, 1, 67), Some(22)); assert_eq!(baby_step_giant_step(7, 1, 45), Some(12)); } #[test] fn primitive_root_tests() { assert_eq!( baby_step_giant_step(3, 311401496, 998244353), Some(178105253) ); assert_eq!( baby_step_giant_step(5, 324637211, 1000000007), Some(976653449) ); } #[test] fn random_numbers() { assert_eq!(baby_step_giant_step(174857, 48604, 150991), Some(177)); assert_eq!(baby_step_giant_step(912103, 53821, 75401), Some(2644)); assert_eq!(baby_step_giant_step(448447, 365819, 671851), Some(23242)); assert_eq!( baby_step_giant_step(220757103, 92430653, 434948279), Some(862704) ); assert_eq!( baby_step_giant_step(176908456, 23538399, 142357679), Some(14215560) ); } #[test] fn no_solution() { assert!(baby_step_giant_step(7, 6, 45).is_none()); assert!(baby_step_giant_step(23, 15, 85).is_none()); assert!(baby_step_giant_step(2, 1, 84).is_none()); } }
{ "argument_definitions": [], "end_line": 41, "name": "trial_division", "signature": "pub fn trial_division(mut num: i128) -> Vec<i128>", "start_line": 10 }
trial_division
pub fn trial_division(mut num: i128) -> Vec<i128> { if num < 0 { return trial_division(-num); } let mut result: Vec<i128> = vec![]; if num == 0 { return result; } while num % 2 == 0 { result.push(2); num /= 2; num = double_to_int(floor(num as f64, 0)) } let mut f: i128 = 3; while f.pow(2) <= num { if num % f == 0 { result.push(f); num /= f; num = double_to_int(floor(num as f64, 0)) } else { f += 2 } } if num != 1 { result.push(num) } result }
Rust-master/src/math/trial_division.rs
fn floor(value: f64, scale: u8) -> f64 { let multiplier = 10i64.pow(scale as u32) as f64; (value * multiplier).floor() } fn double_to_int(amount: f64) -> i128 { amount.round() as i128 } pub fn trial_division(mut num: i128) -> Vec<i128> { if num < 0 { return trial_division(-num); } let mut result: Vec<i128> = vec![]; if num == 0 { return result; } while num % 2 == 0 { result.push(2); num /= 2; num = double_to_int(floor(num as f64, 0)) } let mut f: i128 = 3; while f.pow(2) <= num { if num % f == 0 { result.push(f); num /= f; num = double_to_int(floor(num as f64, 0)) } else { f += 2 } } if num != 1 { result.push(num) } result } #[cfg(test)] mod tests { use super::*; #[test] fn basic() { assert_eq!(trial_division(0), vec![]); assert_eq!(trial_division(1), vec![]); assert_eq!(trial_division(9), vec!(3, 3)); assert_eq!(trial_division(-9), vec!(3, 3)); assert_eq!(trial_division(10), vec!(2, 5)); assert_eq!(trial_division(11), vec!(11)); assert_eq!(trial_division(33), vec!(3, 11)); assert_eq!(trial_division(2003), vec!(2003)); assert_eq!(trial_division(100001), vec!(11, 9091)); } }
{ "argument_definitions": [], "end_line": 27, "name": "zellers_congruence_algorithm", "signature": "pub fn zellers_congruence_algorithm(date: i32, month: i32, year: i32, as_string: bool) -> String", "start_line": 3 }
zellers_congruence_algorithm
pub fn zellers_congruence_algorithm(date: i32, month: i32, year: i32, as_string: bool) -> String { let q = date; let (m, y) = if month < 3 { (month + 12, year - 1) } else { (month, year) }; let day: i32 = (q + (26 * (m + 1) / 10) + (y % 100) + ((y % 100) / 4) + ((y / 100) / 4) + (5 * (y / 100))) % 7; if as_string { number_to_day(day) } else { day.to_string() } /* Note that the day follows the following guidelines: 0 = Saturday 1 = Sunday 2 = Monday 3 = Tuesday 4 = Wednesday 5 = Thursday 6 = Friday */ }
Rust-master/src/math/zellers_congruence_algorithm.rs
// returns the day of the week from the Gregorian Date pub fn zellers_congruence_algorithm(date: i32, month: i32, year: i32, as_string: bool) -> String { let q = date; let (m, y) = if month < 3 { (month + 12, year - 1) } else { (month, year) }; let day: i32 = (q + (26 * (m + 1) / 10) + (y % 100) + ((y % 100) / 4) + ((y / 100) / 4) + (5 * (y / 100))) % 7; if as_string { number_to_day(day) } else { day.to_string() } /* Note that the day follows the following guidelines: 0 = Saturday 1 = Sunday 2 = Monday 3 = Tuesday 4 = Wednesday 5 = Thursday 6 = Friday */ } fn number_to_day(number: i32) -> String { let days = [ "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", ]; String::from(days[number as usize]) } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { assert_eq!(zellers_congruence_algorithm(25, 1, 2013, false), "6"); assert_eq!(zellers_congruence_algorithm(25, 1, 2013, true), "Friday"); assert_eq!(zellers_congruence_algorithm(16, 4, 2022, false), "0"); assert_eq!(zellers_congruence_algorithm(16, 4, 2022, true), "Saturday"); assert_eq!(zellers_congruence_algorithm(14, 12, 1978, false), "5"); assert_eq!(zellers_congruence_algorithm(15, 6, 2021, false), "3"); } }
{ "argument_definitions": [], "end_line": 23, "name": "prime_numbers", "signature": "pub fn prime_numbers(max: usize) -> Vec<usize>", "start_line": 1 }
prime_numbers
pub fn prime_numbers(max: usize) -> Vec<usize> { let mut result: Vec<usize> = Vec::new(); if max >= 2 { result.push(2) } for i in (3..=max).step_by(2) { let stop: usize = (i as f64).sqrt() as usize + 1; let mut status = true; for j in (3..stop).step_by(2) { if i % j == 0 { status = false; break; } } if status { result.push(i) } } result }
Rust-master/src/math/prime_numbers.rs
pub fn prime_numbers(max: usize) -> Vec<usize> { let mut result: Vec<usize> = Vec::new(); if max >= 2 { result.push(2) } for i in (3..=max).step_by(2) { let stop: usize = (i as f64).sqrt() as usize + 1; let mut status = true; for j in (3..stop).step_by(2) { if i % j == 0 { status = false; break; } } if status { result.push(i) } } result } #[cfg(test)] mod tests { use super::*; #[test] fn basic() { assert_eq!(prime_numbers(0), vec![]); assert_eq!(prime_numbers(11), vec![2, 3, 5, 7, 11]); assert_eq!(prime_numbers(25), vec![2, 3, 5, 7, 11, 13, 17, 19, 23]); assert_eq!( prime_numbers(33), vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] ); } }
End of preview. Expand in Data Studio

πŸ“š Tessera: Exposing the Challenges of LLM-based Test Generation for Low-Resource Programming Languages

Tessera is a validation benchmark designed to measure how well models can generate unit tests for Low-Resource Programming Languages (LRPLs) β€” specifically Rust, Go, and Julia.

πŸ“Œ Purpose

Evaluate how well a model can generate test code, given a focal function's source code and additional context.

πŸ“‚ Dataset Structure

Each sample contains:

  • function_name: Name of the focal function.
  • focal_code: Raw source code of the focal function (used for context).
  • function_component: Detail information about the function like function signature,arguments definition,line range,...
  • file_content: Content of file have the focal function.
  • file_path: Relative path to the file in the repository. Additional fields like package_name, wrap_class, class_signature, or struct_class may depending on the programming language. If the language does not use these concepts, the values will be None or empty.

Dataset Size

The dataset contains ~372–412 samples per language, depending on the source repository.

Usage

from datasets import load_dataset
# Load full dataset
dataset = load_dataset("solis-soict/Tessera")
# Load individual language splits
rust_dataset = load_dataset("solis-soict/Tessera", split="rust")
go_dataset = load_dataset("solis-soict/Tessera", split="go")
julia_dataset = load_dataset("solis-soict/Tessera", split="julia")

Additional Information

Other Resources:

  • Github:
  • Paper:

Licence Information

MIT License

Citation Information

Downloads last month
95