Guest User

Untitled

a guest
Jan 24th, 2020
84
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::ops::{AddAssign, MulAssign};
  2. use std::fmt::Display;
  3.  
  4.  
  5. struct Matrix<T: AddAssign + MulAssign + Clone + Display + Copy> {
  6.     rows: usize,
  7.     columns: usize,
  8.     m: Vec<Vec<T>>,
  9. }
  10.  
  11. impl<T: AddAssign + MulAssign + Clone + Display + Copy> Matrix<T> {
  12.     fn from(vector: Vec<Vec<T>>) -> Self {
  13.         Self {
  14.             rows: vector.len(),
  15.             columns: vector[0].len(),
  16.             m: vector,
  17.         }
  18.     }
  19.  
  20.     fn get(&self, row: usize, column: usize) -> &T {
  21.         &self.m[row][column]
  22.     }
  23.  
  24.     fn get_row(&self, row: usize) -> &Vec<T> {
  25.         &self.m[row]
  26.     }
  27.  
  28.     fn set(&mut self, row: usize, column: usize, value: T) {
  29.         self.m[row][column] = value;
  30.     }
  31.  
  32.     fn multiply_row(&mut self, row: usize, value: T) {
  33.         for i in 0..self.columns {
  34.             self.m[row][i] *= value;
  35.         }
  36.     }
  37.  
  38.     fn interchange(&mut self, row1: usize, row2: usize) {
  39.         let temp = self.m[row1].clone();
  40.         self.m[row1] = self.m[row2].clone();
  41.         self.m[row2] = temp;
  42.     }
  43.  
  44.     fn multiply_and_add(&mut self, row1: usize, row2: usize, value: T) {
  45.         let mut row = self.m[row1].clone();
  46.         for n in &mut row {
  47.             *n *= value;
  48.         }
  49.  
  50.         for i in 0..self.columns {
  51.             self.m[row2][i] += row[i];
  52.         }
  53.     }
  54.  
  55.     fn print(&self) {
  56.         print!("┍");
  57.         for _ in 0..self.columns {
  58.             print!("{:5}", " ");
  59.         }
  60.         println!(" ┑");
  61.  
  62.         for row in &self.m {
  63.             print!("│");
  64.             for n in row {
  65.                 print!("{:5}", n);
  66.             }
  67.             println!(" │");
  68.         }
  69.  
  70.         print!("┕");
  71.         for _ in 0..self.columns {
  72.             print!("{:5}", " ");
  73.         }
  74.         println!(" ┙");
  75.     }
  76. }
  77.  
  78.  
  79. fn main() {
  80.     let mut v = vec![vec![0.0, 1.0, 2.0, 3.0],
  81.                      vec![1.0, 2.0, 3.0, 4.0],
  82.                      vec![9.0, 3.2, 5.3, 1.0]];
  83.     let mut m: Matrix = Matrix::from(v);
  84.  
  85.     m.print();
  86. }
RAW Paste Data