-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add problem 2358: Maximum Number of Groups Entering a Competition
- Loading branch information
Showing
3 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
18 changes: 18 additions & 0 deletions
18
src/problem_2358_maximum_number_of_groups_entering_a_competition/mod.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
pub mod newtons_method; | ||
|
||
pub trait Solution { | ||
fn maximum_groups(grades: Vec<i32>) -> i32; | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::Solution; | ||
|
||
pub fn run<S: Solution>() { | ||
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); | ||
} | ||
} | ||
} |
37 changes: 37 additions & 0 deletions
37
src/problem_2358_maximum_number_of_groups_entering_a_competition/newtons_method.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
pub struct Solution; | ||
|
||
// ------------------------------------------------------ snip ------------------------------------------------------ // | ||
|
||
impl Solution { | ||
pub fn maximum_groups(grades: Vec<i32>) -> 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>) -> i32 { | ||
Self::maximum_groups(grades) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
#[test] | ||
fn test_solution() { | ||
super::super::tests::run::<super::Solution>(); | ||
} | ||
} |