diff --git a/src/main.rs b/src/main.rs index e7a11a9..f539d35 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,50 @@ -fn main() { - println!("Hello, world!"); +use std::cmp::min; +use std::io; +use crate::matrix::Matrix; + +mod matrix; + +const ADD_VAL: i32 = 1; +const MATCH_VAL: i32 = 0; + +fn main() -> io::Result<()> { + let str_a = "String A"; + let str_b = "String B"; + + let mut diff_mat = Matrix::new(str_a.len(), str_b.len(), 0i32); + + for col in 1..diff_mat.col_count { + let previous = diff_mat.get(0, col - 1).unwrap(); + diff_mat.set(previous + ADD_VAL, 0, col).expect("Failed to initialize diff matrix"); + } + + for row in 1..diff_mat.row_count { + let previous = diff_mat.get(row - 1, 0).unwrap(); + diff_mat.set(previous - ADD_VAL, row, 0).expect("Failed to initialize diff matrix"); + } + + for row in 1..diff_mat.row_count { + for col in 1..diff_mat.col_count { + let char_a = str_a.chars().nth(row).unwrap(); + let char_b = str_b.chars().nth(col).unwrap(); + + let add_from = diff_mat.get(row, col - 1).unwrap(); + let sub_from = diff_mat.get(row - 1, col).unwrap(); + let substitute_from = diff_mat.get(row - 1, col - 1).unwrap(); + + let add = add_from + ADD_VAL; + let sub = sub_from - ADD_VAL; + let substitute = substitute_from + if char_a == char_b { + MATCH_VAL + } else { + 1 + }; + + let val = min(add, min(sub, substitute)); + diff_mat.set(val, row, col).unwrap(); + } + } + + diff_mat.print(); + Ok(()) } diff --git a/src/matrix.rs b/src/matrix.rs index c40dae8..343ff32 100644 --- a/src/matrix.rs +++ b/src/matrix.rs @@ -1,9 +1,10 @@ +use std::fmt::{Debug, Display, Formatter}; use std::ops; #[derive(Debug)] pub struct Matrix { - row_count: usize, - col_count: usize, + pub row_count: usize, + pub col_count: usize, default_val: T, rows: Vec>, } @@ -52,6 +53,20 @@ impl Matrix where } } +impl Matrix where + T: Display, T: Copy { + pub fn print(&self) { + for row in 0..self.row_count { + for col in 0..self.col_count { + let val = self.rows[row][col]; + print!(" {val} "); + } + + print!("\n"); + } + } +} + impl ops::Add> for Matrix where T: ops::Add, T: Copy { type Output = Result, MatrixError>;