Skip to content

Commit

Permalink
Add problem 1936: Add Minimum Number of Rungs
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 28, 2023
1 parent 40e602a commit abb2aec
Show file tree
Hide file tree
Showing 3 changed files with 62 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 @@ -1358,6 +1358,7 @@ pub mod problem_1922_count_good_numbers;
pub mod problem_1926_nearest_exit_from_entrance_in_maze;
pub mod problem_1929_concatenation_of_array;
pub mod problem_1935_maximum_number_of_words_you_can_type;
pub mod problem_1936_add_minimum_number_of_rungs;
pub mod problem_1941_check_if_all_characters_have_equal_number_of_occurrences;
pub mod problem_1945_sum_of_digits_of_string_after_convert;
pub mod problem_1952_three_divisors;
Expand Down
39 changes: 39 additions & 0 deletions src/problem_1936_add_minimum_number_of_rungs/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
pub struct Solution;

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

use std::num::NonZeroU32;

impl Solution {
pub fn add_rungs(rungs: Vec<i32>, dist: i32) -> i32 {
let dist = NonZeroU32::new(dist as _).unwrap();
let mut result = 0;
let mut prev = 0;

for height in rungs {
let diff = (height - prev) as u32;

result += (diff - 1) / dist;

prev = height;
}

result as _
}
}

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

impl super::Solution for Solution {
fn add_rungs(rungs: Vec<i32>, dist: i32) -> i32 {
Self::add_rungs(rungs, dist)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
22 changes: 22 additions & 0 deletions src/problem_1936_add_minimum_number_of_rungs/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
pub mod iterative;

pub trait Solution {
fn add_rungs(rungs: Vec<i32>, dist: i32) -> i32;
}

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

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

for ((rungs, dist), expected) in test_cases {
assert_eq!(S::add_rungs(rungs.to_vec(), dist), expected);
}
}
}

0 comments on commit abb2aec

Please sign in to comment.