Skip to content

Commit

Permalink
Add problem 1893: Check if All the Integers in a Range Are Covered
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Oct 20, 2023
1 parent 06b3521 commit 1c7ab5a
Show file tree
Hide file tree
Showing 3 changed files with 64 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 @@ -1452,6 +1452,7 @@ pub mod problem_1881_maximum_value_after_insertion;
pub mod problem_1884_egg_drop_with_2_eggs_and_n_floors;
pub mod problem_1886_determine_whether_matrix_can_be_obtained_by_rotation;
pub mod problem_1887_reduction_operations_to_make_the_array_elements_equal;
pub mod problem_1893_check_if_all_the_integers_in_a_range_are_covered;

#[cfg(test)]
mod test_utilities;
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
pub struct Solution;

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

use std::convert::TryInto;

impl Solution {
fn make_range([start, end]: [i32; 2]) -> u64 {
((1 << end) - 1) ^ ((1 << (start - 1)) - 1)
}

pub fn is_covered(ranges: Vec<Vec<i32>>, left: i32, right: i32) -> bool {
let mut covered = 0_u64;

for range in ranges {
covered |= Self::make_range(range.try_into().ok().unwrap());
}

let expected = Self::make_range([left, right]);

covered & expected == expected
}
}

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

impl super::Solution for Solution {
fn is_covered(ranges: Vec<Vec<i32>>, left: i32, right: i32) -> bool {
Self::is_covered(ranges, left, right)
}
}

#[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,24 @@
pub mod iterative;

pub trait Solution {
fn is_covered(ranges: Vec<Vec<i32>>, left: i32, right: i32) -> bool;
}

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

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

for ((ranges, left, right), expected) in test_cases {
assert_eq!(
S::is_covered(ranges.iter().copied().map(Vec::from).collect(), left, right),
expected,
);
}
}
}

0 comments on commit 1c7ab5a

Please sign in to comment.