Advertisement
Guest User

Floyd-Warshall (with Array2D)

a guest
Nov 20th, 2021
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.11 KB | None | 0 0
  1. use std::cmp::min;
  2.  
  3. use rand::{thread_rng, Rng};
  4. use std::time::Instant;
  5.  
  6. use std::ops::{Index, IndexMut};
  7.  
  8. #[derive(Clone)]
  9. struct Array2D<T> {
  10.     m: usize,
  11.     v: Vec<T>,
  12. }
  13.  
  14. impl<T> Array2D<T>
  15. where
  16.     T: Clone,
  17. {
  18.     fn new(empty: T, n: usize, m: usize) -> Self {
  19.         Self {
  20.             m,
  21.             v: vec![empty; n * m],
  22.         }
  23.     }
  24. }
  25.  
  26. impl<T> Index<usize> for Array2D<T> {
  27.     type Output = [T];
  28.  
  29.     fn index(&self, index: usize) -> &Self::Output {
  30.         &self.v[(index) * self.m..(index + 1) * self.m]
  31.     }
  32. }
  33.  
  34. impl<T> IndexMut<usize> for Array2D<T> {
  35.     fn index_mut(&mut self, index: usize) -> &mut Self::Output {
  36.         &mut self.v[(index) * self.m..(index + 1) * self.m]
  37.     }
  38. }
  39.  
  40. /*
  41.   [dist] should contain [n] vectors each of length [n]
  42.  
  43.   dist[i][j] = initial distance between [i] and [j]
  44.  
  45.   After function returns, dist[i][j] contains shortest
  46.   distance between [i] and [j], which could visit other
  47.   vertices
  48. */
  49. fn floyd_warshall(dist: &mut Array2D<i32>) {
  50.     let n = dist.m;
  51.     for i in 0..n {
  52.         for j in 0..n {
  53.             for k in 0..n {
  54.                 dist[j][k] = min(dist[j][k], dist[j][i] + dist[i][k]);
  55.             }
  56.         }
  57.     }
  58. }
  59.  
  60. // Returns hash of final dists
  61. fn test_one_algorithm(
  62.     mut init_dists: Array2D<i32>,
  63.     algo: fn(&mut Array2D<i32>) -> (),
  64.     name: &str,
  65. ) -> i32 {
  66.     let start = Instant::now();
  67.     algo(&mut init_dists);
  68.     let elapsed = start.elapsed().as_millis();
  69.     println!("Algo {} finished in {}ms", name, elapsed);
  70.     let mut hash_sum = 0;
  71.     for row in 0..init_dists.m {
  72.         for val in init_dists[row].iter() {
  73.             hash_sum ^= *val;
  74.         }
  75.     }
  76.     hash_sum
  77. }
  78.  
  79. pub fn main() {
  80.     let n = 750;
  81.     let mut d = Array2D::new(0, n, n);
  82.     let mut rng = thread_rng();
  83.  
  84.     for _ in 1.. {
  85.         for x in 0..n {
  86.             for y in 0..n {
  87.                 d[x][y] = rng.gen_range(0..1_000_000);
  88.             }
  89.             d[x][x] = 0;
  90.         }
  91.         let hash = test_one_algorithm(d.clone(), floyd_warshall, "slow");
  92.         println!("hash: {}", hash);
  93.     }
  94. }
  95.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement