Skip to content

Commit

Permalink
add update matrix & word_pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
phinnl committed May 27, 2024
1 parent 46e1204 commit 60665fe
Show file tree
Hide file tree
Showing 3 changed files with 113 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
pub mod hamming_distance;
pub mod word_pattern;
pub mod update_matrix;
56 changes: 56 additions & 0 deletions src/update_matrix.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
pub fn update_matrix(mat: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
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]]
);
}
}
54 changes: 54 additions & 0 deletions src/word_pattern.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use std::collections::HashMap;

pub fn word_pattern(pattern: String, s: String) -> bool {
let mut map: HashMap<char, &str> = 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()
));
}
}

0 comments on commit 60665fe

Please sign in to comment.