From e0fbca7ff9b2f496d07c1715363d7646052ea966 Mon Sep 17 00:00:00 2001 From: EFanZh Date: Wed, 11 Dec 2024 22:57:39 +0800 Subject: [PATCH] Add problem 2358: Maximum Number of Groups Entering a Competition --- src/lib.rs | 1 + .../mod.rs | 18 +++++++++ .../newtons_method.rs | 37 +++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 src/problem_2358_maximum_number_of_groups_entering_a_competition/mod.rs create mode 100644 src/problem_2358_maximum_number_of_groups_entering_a_competition/newtons_method.rs diff --git a/src/lib.rs b/src/lib.rs index b97ecadf..91e9412c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1749,6 +1749,7 @@ pub mod problem_2351_first_letter_to_appear_twice; pub mod problem_2352_equal_row_and_column_pairs; pub mod problem_2353_design_a_food_rating_system; pub mod problem_2357_make_array_zero_by_subtracting_equal_amounts; +pub mod problem_2358_maximum_number_of_groups_entering_a_competition; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2358_maximum_number_of_groups_entering_a_competition/mod.rs b/src/problem_2358_maximum_number_of_groups_entering_a_competition/mod.rs new file mode 100644 index 00000000..cc7d8106 --- /dev/null +++ b/src/problem_2358_maximum_number_of_groups_entering_a_competition/mod.rs @@ -0,0 +1,18 @@ +pub mod newtons_method; + +pub trait Solution { + fn maximum_groups(grades: Vec) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [(&[10, 6, 12, 7, 3, 5] as &[_], 3), (&[8, 8], 1)]; + + for (grades, expected) in test_cases { + assert_eq!(S::maximum_groups(grades.to_vec()), expected); + } + } +} diff --git a/src/problem_2358_maximum_number_of_groups_entering_a_competition/newtons_method.rs b/src/problem_2358_maximum_number_of_groups_entering_a_competition/newtons_method.rs new file mode 100644 index 00000000..d70d37cb --- /dev/null +++ b/src/problem_2358_maximum_number_of_groups_entering_a_competition/newtons_method.rs @@ -0,0 +1,37 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn maximum_groups(grades: Vec) -> i32 { + let n = grades.len(); + let n_times_2 = n * 2; + let mut guess = n; + + loop { + let new_guess = (guess * guess + n_times_2) / (guess * 2 + 1); + + if new_guess < guess { + guess = new_guess; + } else { + return guess as _; + } + } + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn maximum_groups(grades: Vec) -> i32 { + Self::maximum_groups(grades) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +}