Skip to content

Commit 160e78f

Browse files
committed
Add problem 2639: Find the Width of Columns of a Grid
1 parent f4fe7af commit 160e78f

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1929,6 +1929,7 @@ pub mod problem_2602_minimum_operations_to_make_all_array_elements_equal;
19291929
pub mod problem_2609_find_the_longest_balanced_substring_of_a_binary_string;
19301930
pub mod problem_2610_convert_an_array_into_a_2d_array_with_conditions;
19311931
pub mod problem_2614_prime_in_diagonal;
1932+
pub mod problem_2639_find_the_width_of_columns_of_a_grid;
19321933

19331934
#[cfg(test)]
19341935
mod test_utilities;
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
use std::cmp::Ordering;
6+
7+
impl Solution {
8+
pub fn find_column_width(grid: Vec<Vec<i32>>) -> Vec<i32> {
9+
let columns = grid.first().map_or(0, Vec::len);
10+
11+
(0..columns)
12+
.map(|i| {
13+
grid.iter().fold(0, |max, row| {
14+
let value = row[i];
15+
16+
max.max('block: {
17+
let (abs, extra) = match value.cmp(&0) {
18+
Ordering::Less => (-value, 2),
19+
Ordering::Equal => break 'block 1,
20+
Ordering::Greater => (value, 1),
21+
};
22+
23+
(abs as u32).ilog10() + extra
24+
})
25+
}) as _
26+
})
27+
.collect()
28+
}
29+
}
30+
31+
// ------------------------------------------------------ snip ------------------------------------------------------ //
32+
33+
impl super::Solution for Solution {
34+
fn find_column_width(grid: Vec<Vec<i32>>) -> Vec<i32> {
35+
Self::find_column_width(grid)
36+
}
37+
}
38+
39+
#[cfg(test)]
40+
mod tests {
41+
#[test]
42+
fn test_solution() {
43+
super::super::tests::run::<super::Solution>();
44+
}
45+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn find_column_width(grid: Vec<Vec<i32>>) -> Vec<i32>;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
use crate::test_utilities::Matrix;
11+
12+
pub fn run<S: Solution>() {
13+
let test_cases = [
14+
(&[[1], [22], [333]] as &dyn Matrix<_>, &[3] as &[_]),
15+
(&[[-15, 1, 3], [15, 7, 12], [5, 6, -2]], &[3, 1, 2]),
16+
(
17+
&[
18+
[-4, 0, -1, 3, 9, 8, 6],
19+
[-2, 5, -5, -7, -2, -6, 7],
20+
[4, -4, 1, 7, 0, 6, 8],
21+
[-6, 2, -5, 0, 9, 1, -6],
22+
],
23+
&[2, 2, 2, 2, 2, 2, 2],
24+
),
25+
];
26+
27+
for (grid, expected) in test_cases {
28+
assert_eq!(S::find_column_width(grid.to_vec()), expected);
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)