diff --git a/src/lib.rs b/src/lib.rs index 1c47276..14171f8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -33,4 +33,6 @@ pub mod license_key_formatting; pub mod height_checker; pub mod long_pressed_name; pub mod can_win_nim; -pub mod hamming_distance; \ No newline at end of file +pub mod hamming_distance; +pub mod word_pattern; +pub mod update_matrix; \ No newline at end of file diff --git a/src/update_matrix.rs b/src/update_matrix.rs new file mode 100644 index 0000000..2a6df11 --- /dev/null +++ b/src/update_matrix.rs @@ -0,0 +1,56 @@ +pub fn update_matrix(mat: Vec>) -> Vec> { + let mut matrix = mat; + let rows = matrix.len(); + let cols = matrix[0].len(); + let mut vec = Vec::new(); + + for i in 0..rows { + for j in 0..cols { + if matrix[i][j] == 0 { + vec.push((i, j)); + } + } + } + + for i in 0..rows { + for j in 0..cols { + if matrix[i][j] != 0 { + let mut min = i32::MAX; + for &(x, y) in vec.iter() { + let cur_distance = (i as i32 - x as i32).abs() + (j as i32 - y as i32).abs(); + if i == 2 && j == 1 { + println!("{x} {y} {:?}", cur_distance); + } + if cur_distance < min { + min = cur_distance; + } + } + matrix[i][j] = min; + } + } + } + + matrix +} + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_1() { + assert_eq!( + update_matrix(vec![vec![0, 0, 0], vec![0, 1, 0], vec![0, 0, 0]]), + vec![vec![0, 0, 0], vec![0, 1, 0], vec![0, 0, 0]] + ); + } + + #[test] + fn example_2() { + assert_eq!( + update_matrix(vec![vec![0, 0, 0], vec![0, 1, 0], vec![1, 1, 1]]), + vec![vec![0, 0, 0], vec![0, 1, 0], vec![1, 2, 1]] + ); + } +} \ No newline at end of file diff --git a/src/word_pattern.rs b/src/word_pattern.rs new file mode 100644 index 0000000..65bb619 --- /dev/null +++ b/src/word_pattern.rs @@ -0,0 +1,54 @@ +use std::collections::HashMap; + +pub fn word_pattern(pattern: String, s: String) -> bool { + let mut map: HashMap = HashMap::new(); + let s_by_words: Vec<&str> = s.split(' ').collect(); + + if pattern.len() != s_by_words.len() { + return false; + } + + for i in 0..pattern.len() { + if map.contains_key(&pattern.chars().nth(i).unwrap()) { + if map.get(&pattern.chars().nth(i).unwrap()) != Some(&s_by_words[i]) { + return false; + } + } else { + if map.values().any(|&x| x == s_by_words[i]) { + return false; + } + map.insert(pattern.chars().nth(i).unwrap(), s_by_words[i]); + } + } + + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_1() { + assert!(word_pattern( + "abba".to_string(), + "dog cat cat dog".to_string() + )); + } + + #[test] + fn example_2() { + assert!(!word_pattern( + "abba".to_string(), + "dog cat cat fish".to_string() + )); + } + + #[test] + fn example_3() { + assert!(!word_pattern( + "aaaa".to_string(), + "dog cat cat dog".to_string() + )); + } +}