Skip to content

Commit

Permalink
Add problem 2033: Minimum Operations to Make a Uni-Value Grid
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jan 6, 2024
1 parent d428449 commit d56d847
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1403,6 +1403,7 @@ pub mod problem_2022_convert_1d_array_into_2d_array;
pub mod problem_2027_minimum_moves_to_convert_string;
pub mod problem_2028_find_missing_observations;
pub mod problem_2032_two_out_of_three;
pub mod problem_2033_minimum_operations_to_make_a_uni_value_grid;
pub mod problem_2037_minimum_number_of_moves_to_seat_everyone;
pub mod problem_2038_remove_colored_pieces_if_both_neighbors_are_the_same_color;
pub mod problem_2042_check_if_numbers_are_ascending_in_a_sentence;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::num::NonZeroU32;

impl Solution {
pub fn min_operations(grid: Vec<Vec<i32>>, x: i32) -> i32 {
let x = NonZeroU32::new(x as _).unwrap();
let mut values = Vec::with_capacity(grid.first().map_or(0, Vec::len) * grid.len());
let remainder = grid[0][0] as u32 % x;

for row in grid {
for value in row {
let value = value as u32;

if value % x == remainder {
let value = value / x;

values.push(value);
} else {
return -1;
}
}
}

let n = values.len();
let (left, &mut middle, right) = values.select_nth_unstable(n / 2);
let mut result = 0;

for &mut value in left {
result += middle - value;
}

for &mut value in right {
result += value - middle;
}

result as _
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn min_operations(grid: Vec<Vec<i32>>, x: i32) -> i32 {
Self::min_operations(grid, x)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
pub mod median;

pub trait Solution {
fn min_operations(grid: Vec<Vec<i32>>, x: i32) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;
use crate::test_utilities::Matrix;

pub fn run<S: Solution>() {
let test_cases = [
((&[[2, 4], [6, 8]] as &dyn Matrix<_>, 2), 4),
((&[[1, 5], [2, 3]], 1), 5),
((&[[1, 2], [3, 4]], 2), -1),
];

for ((grid, x), expected) in test_cases {
assert_eq!(S::min_operations(grid.to_vec(), x), expected);
}
}
}

0 comments on commit d56d847

Please sign in to comment.